You can subscribe to this list here.
2000 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(1) |
Nov
(107) |
Dec
(67) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2001 |
Jan
(76) |
Feb
(125) |
Mar
(72) |
Apr
(13) |
May
(18) |
Jun
(12) |
Jul
(129) |
Aug
(47) |
Sep
(1) |
Oct
(36) |
Nov
(128) |
Dec
(124) |
2002 |
Jan
(59) |
Feb
|
Mar
(14) |
Apr
(14) |
May
(72) |
Jun
(9) |
Jul
(3) |
Aug
(5) |
Sep
(18) |
Oct
(65) |
Nov
(28) |
Dec
(12) |
2003 |
Jan
(10) |
Feb
(2) |
Mar
(4) |
Apr
(33) |
May
(21) |
Jun
(9) |
Jul
(29) |
Aug
(34) |
Sep
(4) |
Oct
(8) |
Nov
(15) |
Dec
(4) |
2004 |
Jan
(26) |
Feb
(12) |
Mar
(11) |
Apr
(9) |
May
(7) |
Jun
|
Jul
(5) |
Aug
|
Sep
(3) |
Oct
(7) |
Nov
(1) |
Dec
(10) |
2005 |
Jan
(2) |
Feb
(72) |
Mar
(16) |
Apr
(39) |
May
(48) |
Jun
(97) |
Jul
(57) |
Aug
(13) |
Sep
(16) |
Oct
(24) |
Nov
(100) |
Dec
(24) |
2006 |
Jan
(15) |
Feb
(34) |
Mar
(33) |
Apr
(31) |
May
(79) |
Jun
(64) |
Jul
(41) |
Aug
(64) |
Sep
(31) |
Oct
(46) |
Nov
(55) |
Dec
(37) |
2007 |
Jan
(32) |
Feb
(61) |
Mar
(11) |
Apr
(58) |
May
(46) |
Jun
(30) |
Jul
(94) |
Aug
(93) |
Sep
(86) |
Oct
(69) |
Nov
(125) |
Dec
(177) |
2008 |
Jan
(169) |
Feb
(97) |
Mar
(74) |
Apr
(113) |
May
(120) |
Jun
(334) |
Jul
(215) |
Aug
(237) |
Sep
(72) |
Oct
(189) |
Nov
(126) |
Dec
(160) |
2009 |
Jan
(180) |
Feb
(45) |
Mar
(98) |
Apr
(140) |
May
(151) |
Jun
(71) |
Jul
(107) |
Aug
(119) |
Sep
(73) |
Oct
(121) |
Nov
(14) |
Dec
(6) |
2010 |
Jan
(13) |
Feb
(9) |
Mar
(10) |
Apr
(64) |
May
(3) |
Jun
(16) |
Jul
(7) |
Aug
(23) |
Sep
(17) |
Oct
(37) |
Nov
(5) |
Dec
(8) |
2011 |
Jan
(10) |
Feb
(11) |
Mar
(77) |
Apr
(11) |
May
(2) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <cg...@us...> - 2008-11-23 23:46:15
|
Revision: 5623 http://jython.svn.sourceforge.net/jython/?rev=5623&view=rev Author: cgroves Date: 2008-11-23 23:46:11 +0000 (Sun, 23 Nov 2008) Log Message: ----------- Create the java proxy object after __init__ runs if it wasn't created by __init__ Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/PyArrayDerived.java branches/newstyle-java-types/src/org/python/core/PyBaseExceptionDerived.java branches/newstyle-java-types/src/org/python/core/PyBooleanDerived.java branches/newstyle-java-types/src/org/python/core/PyClassMethodDerived.java branches/newstyle-java-types/src/org/python/core/PyComplexDerived.java branches/newstyle-java-types/src/org/python/core/PyDictionaryDerived.java branches/newstyle-java-types/src/org/python/core/PyEnumerateDerived.java branches/newstyle-java-types/src/org/python/core/PyFileDerived.java branches/newstyle-java-types/src/org/python/core/PyFloatDerived.java branches/newstyle-java-types/src/org/python/core/PyFrozenSetDerived.java branches/newstyle-java-types/src/org/python/core/PyIntegerDerived.java branches/newstyle-java-types/src/org/python/core/PyJavaType.java branches/newstyle-java-types/src/org/python/core/PyListDerived.java branches/newstyle-java-types/src/org/python/core/PyLongDerived.java branches/newstyle-java-types/src/org/python/core/PyModuleDerived.java branches/newstyle-java-types/src/org/python/core/PyObject.java branches/newstyle-java-types/src/org/python/core/PyObjectDerived.java branches/newstyle-java-types/src/org/python/core/PyPropertyDerived.java branches/newstyle-java-types/src/org/python/core/PySetDerived.java branches/newstyle-java-types/src/org/python/core/PySliceDerived.java branches/newstyle-java-types/src/org/python/core/PyStringDerived.java branches/newstyle-java-types/src/org/python/core/PySuperDerived.java branches/newstyle-java-types/src/org/python/core/PyTupleDerived.java branches/newstyle-java-types/src/org/python/core/PyTypeDerived.java branches/newstyle-java-types/src/org/python/core/PyUnicodeDerived.java branches/newstyle-java-types/src/org/python/modules/_collections/PyDefaultDictDerived.java branches/newstyle-java-types/src/org/python/modules/_collections/PyDequeDerived.java branches/newstyle-java-types/src/org/python/modules/_csv/PyDialectDerived.java branches/newstyle-java-types/src/org/python/modules/_functools/PyPartialDerived.java branches/newstyle-java-types/src/org/python/modules/_weakref/ReferenceTypeDerived.java branches/newstyle-java-types/src/org/python/modules/random/PyRandomDerived.java branches/newstyle-java-types/src/org/python/modules/thread/PyLocalDerived.java branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporterDerived.java branches/newstyle-java-types/src/templates/object.derived Modified: branches/newstyle-java-types/src/org/python/core/PyArrayDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyArrayDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyArrayDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyBaseExceptionDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyBaseExceptionDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyBaseExceptionDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1069,6 +1069,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyBooleanDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyBooleanDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyBooleanDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyClassMethodDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyClassMethodDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyClassMethodDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyComplexDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyComplexDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyComplexDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyDictionaryDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyDictionaryDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyDictionaryDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyEnumerateDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyEnumerateDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyEnumerateDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyFileDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyFileDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyFileDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyFloatDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyFloatDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyFloatDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyFrozenSetDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyFrozenSetDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyFrozenSetDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyIntegerDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyIntegerDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyIntegerDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -29,7 +29,7 @@ @Override public Class<?> getProxyType() { - return underlying_class; + return PyObject.class.isAssignableFrom(underlying_class) ? null : underlying_class; } @Override Modified: branches/newstyle-java-types/src/org/python/core/PyListDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyListDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyListDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyLongDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyLongDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyLongDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyModuleDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyModuleDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyModuleDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1069,6 +1069,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyObject.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -101,8 +101,48 @@ * Dispatch __init__ behavior */ public void dispatch__init__(PyType type,PyObject[] args,String[] keywords) { + proxyInit(); } + /** + * Attempts to automatically initialize our Java proxy if we have one and it wasn't initialized + * by our __init__. + */ + protected void proxyInit() { + if (javaProxy != null || getType().getProxyType() == null) { + return; + } + Class<?> c = getType().getProxyType(); + PyProxy proxy; + ThreadState ts = Py.getThreadState(); + try { + ts.pushInitializingProxy(this); + try { + proxy = (PyProxy)c.newInstance(); + } catch (java.lang.InstantiationException e) { + Class<?> sup = c.getSuperclass(); + String msg = "Default constructor failed for Java superclass"; + if (sup != null) { + msg += " " + sup.getName(); + } + throw Py.TypeError(msg); + } catch (NoSuchMethodError nsme) { + throw Py.TypeError("constructor requires arguments"); + } catch (Exception exc) { + throw Py.JavaError(exc); + } + } finally { + ts.popInitializingProxy(); + } + if (javaProxy != null && javaProxy != proxy) { + throw Py.TypeError("Proxy instance already initialized"); + } + PyObject proxyInstance = proxy._getPyInstance(); + if (proxyInstance != null && proxyInstance != this) { + throw Py.TypeError("Proxy initialized with another instance"); + } + javaProxy = proxy; + } /** * Equivalent to the standard Python __repr__ method. This method Modified: branches/newstyle-java-types/src/org/python/core/PyObjectDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyObjectDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyObjectDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyPropertyDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyPropertyDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyPropertyDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PySetDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PySetDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PySetDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PySliceDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PySliceDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PySliceDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyStringDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyStringDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyStringDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PySuperDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PySuperDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PySuperDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyTupleDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyTupleDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyTupleDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyTypeDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyTypeDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyTypeDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1069,6 +1069,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyUnicodeDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyUnicodeDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/core/PyUnicodeDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1093,6 +1093,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/_collections/PyDefaultDictDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/_collections/PyDefaultDictDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/modules/_collections/PyDefaultDictDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1095,6 +1095,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/_collections/PyDequeDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/_collections/PyDequeDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/modules/_collections/PyDequeDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1095,6 +1095,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/_csv/PyDialectDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/_csv/PyDialectDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/modules/_csv/PyDialectDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1071,6 +1071,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/_functools/PyPartialDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/_functools/PyPartialDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/modules/_functools/PyPartialDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1071,6 +1071,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/_weakref/ReferenceTypeDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1095,6 +1095,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/random/PyRandomDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/random/PyRandomDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/modules/random/PyRandomDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1095,6 +1095,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/thread/PyLocalDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/thread/PyLocalDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/modules/thread/PyLocalDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1071,6 +1071,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporterDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporterDerived.java 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporterDerived.java 2008-11-23 23:46:11 UTC (rev 5623) @@ -1071,6 +1071,7 @@ } } } + proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/templates/object.derived =================================================================== --- branches/newstyle-java-types/src/templates/object.derived 2008-11-23 23:12:46 UTC (rev 5622) +++ branches/newstyle-java-types/src/templates/object.derived 2008-11-23 23:46:11 UTC (rev 5623) @@ -428,6 +428,7 @@ } } } + proxyInit(); } public PyObject __index__() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-23 23:12:51
|
Revision: 5622 http://jython.svn.sourceforge.net/jython/?rev=5622&view=rev Author: cgroves Date: 2008-11-23 23:12:46 +0000 (Sun, 23 Nov 2008) Log Message: ----------- PyInstance ignored __tojava__ methods on its classes, so Java classes in the old world with a __tojava__ would be ignored as well. This differed from most other dunder methods, so the new PyJavaType exposes __tojava__ through PyObjectDerived. IOBase was using __tojava__ to mean something different than what PyObject was doing with it, so change the name to keep regular jython object conversion from picking up on it. Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/PyFile.java branches/newstyle-java-types/src/org/python/core/io/BufferedIOMixin.java branches/newstyle-java-types/src/org/python/core/io/FileIO.java branches/newstyle-java-types/src/org/python/core/io/IOBase.java branches/newstyle-java-types/src/org/python/core/io/StreamIO.java branches/newstyle-java-types/src/org/python/core/io/TextIOBase.java Modified: branches/newstyle-java-types/src/org/python/core/PyFile.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyFile.java 2008-11-23 22:22:05 UTC (rev 5621) +++ branches/newstyle-java-types/src/org/python/core/PyFile.java 2008-11-23 23:12:46 UTC (rev 5622) @@ -529,7 +529,12 @@ } public Object __tojava__(Class<?> cls) { - Object o = file.__tojava__(cls); + Object o = null; + if (InputStream.class.isAssignableFrom(cls)) { + o = file.asInputStream(); + } else if (OutputStream.class.isAssignableFrom(cls)) { + o = file.asOutputStream(); + } if (o == null) { o = super.__tojava__(cls); } Modified: branches/newstyle-java-types/src/org/python/core/io/BufferedIOMixin.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/io/BufferedIOMixin.java 2008-11-23 22:22:05 UTC (rev 5621) +++ branches/newstyle-java-types/src/org/python/core/io/BufferedIOMixin.java 2008-11-23 23:12:46 UTC (rev 5622) @@ -1,6 +1,9 @@ /* Copyright (c) 2007 Jython Developers */ package org.python.core.io; +import java.io.InputStream; +import java.io.OutputStream; + import org.python.core.Py; import org.python.core.PyException; @@ -102,8 +105,13 @@ return rawIO.closed(); } - /** {@inheritDoc} */ - public Object __tojava__(Class cls) { - return rawIO.__tojava__(cls); + @Override + public InputStream asInputStream() { + return rawIO.asInputStream(); } + + @Override + public OutputStream asOutputStream() { + return rawIO.asOutputStream(); + } } Modified: branches/newstyle-java-types/src/org/python/core/io/FileIO.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/io/FileIO.java 2008-11-23 22:22:05 UTC (rev 5621) +++ branches/newstyle-java-types/src/org/python/core/io/FileIO.java 2008-11-23 23:12:46 UTC (rev 5622) @@ -14,7 +14,6 @@ import org.python.core.imp; import org.python.core.Py; -import org.python.core.PyObject; import org.python.core.util.RelativeFile; import org.python.modules.errno; @@ -27,7 +26,7 @@ /** The underlying file channel */ private FileChannel fileChannel; - + /** The underlying file (if known) */ private RandomAccessFile file; @@ -336,16 +335,16 @@ super.close(); } - /** {@inheritDoc} */ - public Object __tojava__(Class cls) { - if (OutputStream.class.isAssignableFrom(cls) && writing) { - return Channels.newOutputStream(fileChannel); - } else if (InputStream.class.isAssignableFrom(cls) && readable()) { - return Channels.newInputStream(fileChannel); - } - return super.__tojava__(cls); + @Override + public OutputStream asOutputStream() { + return writing ? Channels.newOutputStream(fileChannel) : super.asOutputStream(); } + @Override + public InputStream asInputStream() { + return readable() ? Channels.newInputStream(fileChannel) : super.asInputStream(); + } + /** {@inheritDoc} */ public boolean readable() { return reading || plus; Modified: branches/newstyle-java-types/src/org/python/core/io/IOBase.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/io/IOBase.java 2008-11-23 22:22:05 UTC (rev 5621) +++ branches/newstyle-java-types/src/org/python/core/io/IOBase.java 2008-11-23 23:12:46 UTC (rev 5622) @@ -1,6 +1,9 @@ /* Copyright (c) 2007 Jython Developers */ package org.python.core.io; +import java.io.InputStream; +import java.io.OutputStream; + import org.python.core.Py; import org.python.core.PyException; import org.python.modules.errno; @@ -191,17 +194,20 @@ } /** - * Coerce this Python object (the parent PyFile) into a java - * object. - * - * @param cls the desired Class to coerce the object to - * @return the desired object or null + * Coerce this into an OutputStream if possible, or return null. */ - public Object __tojava__(Class cls) { + public OutputStream asOutputStream() { return null; } /** + * Coerce this into an InputStream if possible, or return null. + */ + public InputStream asInputStream() { + return null; + } + + /** * Raise a TypeError indicating the specified operation is not * supported. * Modified: branches/newstyle-java-types/src/org/python/core/io/StreamIO.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/io/StreamIO.java 2008-11-23 22:22:05 UTC (rev 5621) +++ branches/newstyle-java-types/src/org/python/core/io/StreamIO.java 2008-11-23 23:12:46 UTC (rev 5622) @@ -18,7 +18,6 @@ import org.python.core.imp; import org.python.core.Py; -import org.python.core.PyObject; /** * Raw I/O implementation for simple streams. @@ -158,7 +157,7 @@ } super.close(); } - + /** Unwrap one or more nested FilterInputStreams. */ private static FileDescriptor getInputFileDescriptor(InputStream stream) throws IOException { if (stream == null) @@ -200,12 +199,12 @@ } return null; } - + /** {@inheritDoc} */ - + public boolean isatty() { checkClosed(); - + FileDescriptor fd; try { if ( ((fd = getInputFileDescriptor(inputStream)) == null) && @@ -214,7 +213,7 @@ } catch (IOException e) { return false; } - + return imp.load("os").__getattr__("isatty").__call__(Py.java2py(fd)).__nonzero__(); } @@ -228,20 +227,26 @@ return writeChannel != null; } - /** {@inheritDoc} */ - public Object __tojava__(Class cls) { - if (OutputStream.class.isAssignableFrom(cls) && writable()) { + @Override + public OutputStream asOutputStream() { + if (writable()) { if (outputStream == null) { return Channels.newOutputStream(writeChannel); } return outputStream; - } else if (InputStream.class.isAssignableFrom(cls) && readable()) { + } + return super.asOutputStream(); + } + + @Override + public InputStream asInputStream() { + if (readable()) { if (inputStream == null) { return Channels.newInputStream(readChannel); } return inputStream; } - return super.__tojava__(cls); + return super.asInputStream(); } /** {@inheritDoc} */ Modified: branches/newstyle-java-types/src/org/python/core/io/TextIOBase.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/io/TextIOBase.java 2008-11-23 22:22:05 UTC (rev 5621) +++ branches/newstyle-java-types/src/org/python/core/io/TextIOBase.java 2008-11-23 23:12:46 UTC (rev 5622) @@ -1,6 +1,8 @@ /* Copyright (c) 2007 Jython Developers */ package org.python.core.io; +import java.io.InputStream; +import java.io.OutputStream; import java.nio.ByteBuffer; import org.python.core.Py; @@ -188,11 +190,16 @@ return bufferedIO.closed(); } - /** {@inheritDoc} */ - public Object __tojava__(Class cls) { - return bufferedIO.__tojava__(cls); + @Override + public InputStream asInputStream() { + return bufferedIO.asInputStream(); } + @Override + public OutputStream asOutputStream() { + return bufferedIO.asOutputStream(); + } + /** * Return the known Newline types, as a PyObject, encountered * while reading this file. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-23 22:22:07
|
Revision: 5621 http://jython.svn.sourceforge.net/jython/?rev=5621&view=rev Author: pjenvey Date: 2008-11-23 22:22:05 +0000 (Sun, 23 Nov 2008) Log Message: ----------- don't buffer the various popen2 helper streams in hopes to make test_cmd_line less flakey Modified Paths: -------------- trunk/jython/Lib/popen2.py Modified: trunk/jython/Lib/popen2.py =================================================================== --- trunk/jython/Lib/popen2.py 2008-11-23 21:56:25 UTC (rev 5620) +++ trunk/jython/Lib/popen2.py 2008-11-23 22:22:05 UTC (rev 5621) @@ -44,7 +44,7 @@ the close method. """ def __init__(self, stream, process, name): - self._file = FileUtil.wrap(stream) + self._file = FileUtil.wrap(stream, 0) self._process = process def __getattr__(self, name): @@ -93,10 +93,10 @@ bufsize ) - self.tochild = FileUtil.wrap(self._tochild) - self.fromchild = FileUtil.wrap(self._fromchild) + self.tochild = FileUtil.wrap(self._tochild, 0) + self.fromchild = FileUtil.wrap(self._fromchild, 0) if self._childerr: - self.childerr = FileUtil.wrap(self._childerr) + self.childerr = FileUtil.wrap(self._childerr, 0) def _startChildWaiter(self): """Start a subthread that waits for the child process to exit.""" @@ -198,7 +198,7 @@ "%s-stderr" % self.process, self._close ) - return FileUtil.wrap(joinedStream) + return FileUtil.wrap(joinedStream, 0) def _close( self ): """Must be closed twice (once for each of the two joined pipes)""" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-23 21:56:27
|
Revision: 5620 http://jython.svn.sourceforge.net/jython/?rev=5620&view=rev Author: pjenvey Date: 2008-11-23 21:56:25 +0000 (Sun, 23 Nov 2008) Log Message: ----------- turn on javatest/regrtest junit xml output by default, to dist/testreports Modified Paths: -------------- trunk/jython/build.xml Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2008-11-23 20:58:25 UTC (rev 5619) +++ trunk/jython/build.xml 2008-11-23 21:56:25 UTC (rev 5620) @@ -152,6 +152,7 @@ <property name="gensrc.dir" value="${output.dir}/gensrc" /> <property name="dist.dir" value="${work.dir}/dist" /> <property name="apidoc.dir" value="${dist.dir}/Doc/javadoc" /> + <property name="junit.reports" value="${dist.dir}/testreports" /> <!-- classpaths --> <path id="main.classpath"> @@ -761,11 +762,17 @@ </jar> </target> - <target name="test" depends="javatest,launchertest,regrtest"/> + <target name="test" depends="prepare-test,javatest,launchertest,regrtest"/> + <target name="prepare-test" depends="init"> + <!-- Clean any old test output --> + <delete dir="${junit.reports}"/> + </target> <target name="javatest" depends="compile,expose"> + <mkdir dir="${junit.reports}"/> <junit fork="true" printsummary="true"> + <formatter type="xml"/> <classpath refid="test.classpath"/> - <batchtest todir="${dist.dir}/testreports"> + <batchtest todir="${junit.reports}"> <fileset dir="${test.source.dir}" includes="**/*Test*.java"> <exclude name="javatests/**/*" /> <exclude name="**/InterpTestCase.java" /> @@ -787,6 +794,8 @@ <arg value="${dist.dir}/Lib/test/regrtest.py"/> <!-- Only run the tests that are expected to work on Jython --> <arg value="--expected"/> + <arg value="-j"/> + <arg value="${junit.reports}"/> </exec> </target> <target name="regrtest-windows" if="os.family.windows"> @@ -795,6 +804,8 @@ <arg value="${dist.dir}/Lib/test/regrtest.py"/> <!-- Only run the tests that are expected to work on Jython --> <arg value="--expected"/> + <arg value="-j"/> + <arg value="${junit.reports}"/> </exec> </target> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-23 20:58:26
|
Revision: 5619 http://jython.svn.sourceforge.net/jython/?rev=5619&view=rev Author: pjenvey Date: 2008-11-23 20:58:25 +0000 (Sun, 23 Nov 2008) Log Message: ----------- fix bit rot in the Expose javatests: ensure we setType new descriptors, init sys when needed, fix null method docs (use "" instead) Modified Paths: -------------- trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java Modified: trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java 2008-11-23 19:35:19 UTC (rev 5618) +++ trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java 2008-11-23 20:58:25 UTC (rev 5619) @@ -28,7 +28,7 @@ new String[0], new String[0], MethodType.DEFAULT, - null); + ""); } public InstanceMethodExposer(Type onType, Modified: trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java 2008-11-23 19:35:19 UTC (rev 5618) +++ trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java 2008-11-23 20:58:25 UTC (rev 5619) @@ -33,7 +33,9 @@ DescriptorExposer de = new DescriptorExposer(ASM_TYPE, name); setup.setup(de); Class descriptor = de.load(new BytecodeLoader.Loader()); - return (PyDataDescr)descriptor.newInstance(); + PyDataDescr descr = (PyDataDescr)descriptor.newInstance(); + descr.setType(PY_TYPE); + return descr; } public PyDataDescr makeDescriptor(DescSetup setup) throws Exception { Modified: trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java 2008-11-23 19:35:19 UTC (rev 5618) +++ trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java 2008-11-23 20:58:25 UTC (rev 5619) @@ -11,7 +11,7 @@ import org.python.core.PyObject; import org.python.core.PyType; -public class ExposedTypeProcessorTest extends TestCase { +public class ExposedTypeProcessorTest extends InterpTestCase { public void testDetectType() throws Exception { InputStream in = getClass().getClassLoader() @@ -41,6 +41,7 @@ PyBuiltinCallable bound = func.bind(simp); bound.__call__(); PyDataDescr desc = (PyDataDescr)tostringDesc.newInstance(); + desc.setType(simp.getType()); assertEquals(doctoredSimple.getField("toStringVal").get(simp), desc.__get__(simp, PyType.fromClass(doctoredSimple)).toString()); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-23 19:35:21
|
Revision: 5618 http://jython.svn.sourceforge.net/jython/?rev=5618&view=rev Author: pjenvey Date: 2008-11-23 19:35:19 +0000 (Sun, 23 Nov 2008) Log Message: ----------- exclude the antlr tests as they don't have any actual tests Modified Paths: -------------- trunk/jython/build.xml Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2008-11-23 15:22:58 UTC (rev 5617) +++ trunk/jython/build.xml 2008-11-23 19:35:19 UTC (rev 5618) @@ -769,6 +769,7 @@ <fileset dir="${test.source.dir}" includes="**/*Test*.java"> <exclude name="javatests/**/*" /> <exclude name="**/InterpTestCase.java" /> + <exclude name="org/python/antlr/**" /> </fileset> </batchtest> </junit> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-11-23 15:23:00
|
Revision: 5617 http://jython.svn.sourceforge.net/jython/?rev=5617&view=rev Author: fwierzbicki Date: 2008-11-23 15:22:58 +0000 (Sun, 23 Nov 2008) Log Message: ----------- jythonc branch superseded by newstyle-java-types branch. Removed Paths: ------------- branches/jythonc/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-11-23 15:02:12
|
Revision: 5616 http://jython.svn.sourceforge.net/jython/?rev=5616&view=rev Author: fwierzbicki Date: 2008-11-23 15:02:10 +0000 (Sun, 23 Nov 2008) Log Message: ----------- Removed merge tracking for "svnmerge" for https://jython.svn.sourceforge.net/svnroot/jython/branches/nowalker Property Changed: ---------------- trunk/jython/ Property changes on: trunk/jython ___________________________________________________________________ Deleted: svnmerge-integrated - /branches/nowalker:1-5263 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-11-23 14:49:35
|
Revision: 5615 http://jython.svn.sourceforge.net/jython/?rev=5615&view=rev Author: fwierzbicki Date: 2008-11-23 14:49:27 +0000 (Sun, 23 Nov 2008) Log Message: ----------- Merged revisions 5593,5596,5598-5604,5606,5608-5611 via svnmerge from https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython Modified Paths: -------------- branches/astwrite/Lib/inspect.py branches/astwrite/Lib/test/test_chdir.py branches/astwrite/Lib/test/test_descr.py branches/astwrite/Lib/test/test_import_jy.py branches/astwrite/Lib/test/test_inspect.py branches/astwrite/Lib/zlib.py branches/astwrite/src/com/ziclix/python/sql/Fetch.java branches/astwrite/src/com/ziclix/python/sql/Procedure.java branches/astwrite/src/com/ziclix/python/sql/PyCursor.java branches/astwrite/src/com/ziclix/python/sql/PyStatement.java branches/astwrite/src/org/python/compiler/CodeCompiler.java branches/astwrite/src/org/python/compiler/Module.java branches/astwrite/src/org/python/core/Py.java branches/astwrite/src/org/python/core/PyArray.java branches/astwrite/src/org/python/core/PyFile.java branches/astwrite/src/org/python/core/PyObject.java branches/astwrite/src/org/python/core/PySequence.java branches/astwrite/src/org/python/core/PyString.java branches/astwrite/src/org/python/core/PySystemState.java branches/astwrite/src/org/python/core/__builtin__.java branches/astwrite/src/org/python/core/imp.java branches/astwrite/src/org/python/core/util/FileUtil.java branches/astwrite/src/org/python/modules/_codecs.java branches/astwrite/src/org/python/modules/imp.java branches/astwrite/src/org/python/modules/struct.java branches/astwrite/src/org/python/modules/thread/thread.java branches/astwrite/src/org/python/modules/time/PyTimeTuple.java branches/astwrite/src/org/python/modules/time/Time.java Added Paths: ----------- branches/astwrite/Lib/pydoc.py branches/astwrite/Lib/warnings.py Property Changed: ---------------- branches/astwrite/ Property changes on: branches/astwrite ___________________________________________________________________ Modified: svnmerge-integrated - /trunk/jython:1-5584 + /trunk/jython:1-5614 Modified: branches/astwrite/Lib/inspect.py =================================================================== --- branches/astwrite/Lib/inspect.py 2008-11-23 14:16:31 UTC (rev 5614) +++ branches/astwrite/Lib/inspect.py 2008-11-23 14:49:27 UTC (rev 5615) @@ -383,6 +383,8 @@ filename = getfile(object) if string.lower(filename[-4:]) in ('.pyc', '.pyo'): filename = filename[:-4] + '.py' + elif filename.endswith('$py.class'): + filename = filename[:-9] + '.py' for suffix, mode, kind in imp.get_suffixes(): if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: # Looks like a binary file. We want to only return a text file. Copied: branches/astwrite/Lib/pydoc.py (from rev 5611, trunk/jython/Lib/pydoc.py) =================================================================== --- branches/astwrite/Lib/pydoc.py (rev 0) +++ branches/astwrite/Lib/pydoc.py 2008-11-23 14:49:27 UTC (rev 5615) @@ -0,0 +1,2257 @@ +#!/usr/bin/env python +# -*- coding: Latin-1 -*- +"""Generate Python documentation in HTML or text for interactive use. + +In the Python interpreter, do "from pydoc import help" to provide online +help. Calling help(thing) on a Python object documents the object. + +Or, at the shell command line outside of Python: + +Run "pydoc <name>" to show documentation on something. <name> may be +the name of a function, module, package, or a dotted reference to a +class or function within a module or module in a package. If the +argument contains a path segment delimiter (e.g. slash on Unix, +backslash on Windows) it is treated as the path to a Python source file. + +Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines +of all available modules. + +Run "pydoc -p <port>" to start an HTTP server on a given port on the +local machine to generate documentation web pages. + +For platforms without a command line, "pydoc -g" starts the HTTP server +and also pops up a little window for controlling it. + +Run "pydoc -w <name>" to write out the HTML documentation for a module +to a file named "<name>.html". + +Module docs for core modules are assumed to be in + + http://www.python.org/doc/current/lib/ + +This can be overridden by setting the PYTHONDOCS environment variable +to a different URL or to a local directory containing the Library +Reference Manual pages. +""" + +__author__ = "Ka-Ping Yee <pi...@lf...>" +__date__ = "26 February 2001" + +__version__ = "$Revision: 54366 $" +__credits__ = """Guido van Rossum, for an excellent programming language. +Tommy Burnette, the original creator of manpy. +Paul Prescod, for all his work on onlinehelp. +Richard Chamberlain, for the first implementation of textdoc. +""" + +# Known bugs that can't be fixed here: +# - imp.load_module() cannot be prevented from clobbering existing +# loaded modules, so calling synopsis() on a binary module file +# changes the contents of any existing module with the same name. +# - If the __file__ attribute on a module is a relative path and +# the current directory is changed with os.chdir(), an incorrect +# path will be displayed. + +import sys, imp, os, re, types, inspect, __builtin__, pkgutil +from repr import Repr +from string import expandtabs, find, join, lower, split, strip, rfind, rstrip +try: + from collections import deque +except ImportError: + # Python 2.3 compatibility + class deque(list): + def popleft(self): + return self.pop(0) + +# --------------------------------------------------------- common routines + +def pathdirs(): + """Convert sys.path into a list of absolute, existing, unique paths.""" + dirs = [] + normdirs = [] + for dir in sys.path: + dir = os.path.abspath(dir or '.') + normdir = os.path.normcase(dir) + if normdir not in normdirs and os.path.isdir(dir): + dirs.append(dir) + normdirs.append(normdir) + return dirs + +def getdoc(object): + """Get the doc string or comments for an object.""" + result = inspect.getdoc(object) or inspect.getcomments(object) + return result and re.sub('^ *\n', '', rstrip(result)) or '' + +def splitdoc(doc): + """Split a doc string into a synopsis line (if any) and the rest.""" + lines = split(strip(doc), '\n') + if len(lines) == 1: + return lines[0], '' + elif len(lines) >= 2 and not rstrip(lines[1]): + return lines[0], join(lines[2:], '\n') + return '', join(lines, '\n') + +def classname(object, modname): + """Get a class name and qualify it with a module name if necessary.""" + name = object.__name__ + if object.__module__ != modname: + name = object.__module__ + '.' + name + return name + +def isdata(object): + """Check if an object is of a type that probably means it's data.""" + return not (inspect.ismodule(object) or inspect.isclass(object) or + inspect.isroutine(object) or inspect.isframe(object) or + inspect.istraceback(object) or inspect.iscode(object)) + +def replace(text, *pairs): + """Do a series of global replacements on a string.""" + while pairs: + text = join(split(text, pairs[0]), pairs[1]) + pairs = pairs[2:] + return text + +def cram(text, maxlen): + """Omit part of a string if needed to make it fit in a maximum length.""" + if len(text) > maxlen: + pre = max(0, (maxlen-3)//2) + post = max(0, maxlen-3-pre) + return text[:pre] + '...' + text[len(text)-post:] + return text + +_re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE) +def stripid(text): + """Remove the hexadecimal id from a Python object representation.""" + # The behaviour of %p is implementation-dependent in terms of case. + if _re_stripid.search(repr(Exception)): + return _re_stripid.sub(r'\1', text) + return text + +def _is_some_method(obj): + return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) + +def allmethods(cl): + methods = {} + for key, value in inspect.getmembers(cl, _is_some_method): + methods[key] = 1 + for base in cl.__bases__: + methods.update(allmethods(base)) # all your base are belong to us + for key in methods.keys(): + methods[key] = getattr(cl, key) + return methods + +def _split_list(s, predicate): + """Split sequence s via predicate, and return pair ([true], [false]). + + The return value is a 2-tuple of lists, + ([x for x in s if predicate(x)], + [x for x in s if not predicate(x)]) + """ + + yes = [] + no = [] + for x in s: + if predicate(x): + yes.append(x) + else: + no.append(x) + return yes, no + +def visiblename(name, all=None): + """Decide whether to show documentation on a variable.""" + # Certain special names are redundant. + if name in ('__builtins__', '__doc__', '__file__', '__path__', + '__module__', '__name__', '__slots__'): return 0 + # Private names are hidden, but special names are displayed. + if name.startswith('__') and name.endswith('__'): return 1 + if all is not None: + # only document that which the programmer exported in __all__ + return name in all + else: + return not name.startswith('_') + +def classify_class_attrs(object): + """Wrap inspect.classify_class_attrs, with fixup for data descriptors.""" + def fixup((name, kind, cls, value)): + if inspect.isdatadescriptor(value): + kind = 'data descriptor' + return name, kind, cls, value + return map(fixup, inspect.classify_class_attrs(object)) + +# ----------------------------------------------------- module manipulation + +def ispackage(path): + """Guess whether a path refers to a package directory.""" + if os.path.isdir(path): + for ext in ('.py', '.pyc', '.pyo', '$py.class'): + if os.path.isfile(os.path.join(path, '__init__' + ext)): + return True + return False + +def source_synopsis(file): + line = file.readline() + while line[:1] == '#' or not strip(line): + line = file.readline() + if not line: break + line = strip(line) + if line[:4] == 'r"""': line = line[1:] + if line[:3] == '"""': + line = line[3:] + if line[-1:] == '\\': line = line[:-1] + while not strip(line): + line = file.readline() + if not line: break + result = strip(split(line, '"""')[0]) + else: result = None + return result + +def synopsis(filename, cache={}): + """Get the one-line summary out of a module file.""" + mtime = os.stat(filename).st_mtime + lastupdate, result = cache.get(filename, (0, None)) + if lastupdate < mtime: + info = inspect.getmoduleinfo(filename) + try: + file = open(filename) + except IOError: + # module can't be opened, so skip it + return None + if info and 'b' in info[2]: # binary modules have to be imported + try: module = imp.load_module('__temp__', file, filename, info[1:]) + except: return None + result = (module.__doc__ or '').splitlines()[0] + del sys.modules['__temp__'] + else: # text modules can be directly examined + result = source_synopsis(file) + file.close() + cache[filename] = (mtime, result) + return result + +class ErrorDuringImport(Exception): + """Errors that occurred while trying to import something to document it.""" + def __init__(self, filename, (exc, value, tb)): + self.filename = filename + self.exc = exc + self.value = value + self.tb = tb + + def __str__(self): + exc = self.exc + if type(exc) is types.ClassType: + exc = exc.__name__ + return 'problem in %s - %s: %s' % (self.filename, exc, self.value) + +def importfile(path): + """Import a Python source file or compiled file given its path.""" + magic = imp.get_magic() + file = open(path, 'r') + if file.read(len(magic)) == magic: + kind = imp.PY_COMPILED + else: + kind = imp.PY_SOURCE + file.close() + filename = os.path.basename(path) + name, ext = os.path.splitext(filename) + file = open(path, 'r') + try: + module = imp.load_module(name, file, path, (ext, 'r', kind)) + except: + raise ErrorDuringImport(path, sys.exc_info()) + file.close() + return module + +def safeimport(path, forceload=0, cache={}): + """Import a module; handle errors; return None if the module isn't found. + + If the module *is* found but an exception occurs, it's wrapped in an + ErrorDuringImport exception and reraised. Unlike __import__, if a + package path is specified, the module at the end of the path is returned, + not the package at the beginning. If the optional 'forceload' argument + is 1, we reload the module from disk (unless it's a dynamic extension).""" + try: + # If forceload is 1 and the module has been previously loaded from + # disk, we always have to reload the module. Checking the file's + # mtime isn't good enough (e.g. the module could contain a class + # that inherits from another module that has changed). + if forceload and path in sys.modules: + if path not in sys.builtin_module_names: + # Avoid simply calling reload() because it leaves names in + # the currently loaded module lying around if they're not + # defined in the new source file. Instead, remove the + # module from sys.modules and re-import. Also remove any + # submodules because they won't appear in the newly loaded + # module's namespace if they're already in sys.modules. + subs = [m for m in sys.modules if m.startswith(path + '.')] + for key in [path] + subs: + # Prevent garbage collection. + cache[key] = sys.modules[key] + del sys.modules[key] + module = __import__(path) + except: + # Did the error occur before or after the module was found? + (exc, value, tb) = info = sys.exc_info() + if path in sys.modules: + # An error occurred while executing the imported module. + raise ErrorDuringImport(sys.modules[path].__file__, info) + elif exc is SyntaxError: + # A SyntaxError occurred before we could execute the module. + raise ErrorDuringImport(value.filename, info) + elif exc is ImportError and \ + split(lower(str(value)))[:2] == ['no', 'module']: + # The module was not found. + return None + else: + # Some other error occurred during the importing process. + raise ErrorDuringImport(path, sys.exc_info()) + for part in split(path, '.')[1:]: + try: module = getattr(module, part) + except AttributeError: return None + return module + +# ---------------------------------------------------- formatter base class + +class Doc: + def document(self, object, name=None, *args): + """Generate documentation for an object.""" + args = (object, name) + args + # 'try' clause is to attempt to handle the possibility that inspect + # identifies something in a way that pydoc itself has issues handling; + # think 'super' and how it is a descriptor (which raises the exception + # by lacking a __name__ attribute) and an instance. + if inspect.isgetsetdescriptor(object): return self.docdata(*args) + if inspect.ismemberdescriptor(object): return self.docdata(*args) + try: + if inspect.ismodule(object): return self.docmodule(*args) + if inspect.isclass(object): return self.docclass(*args) + if inspect.isroutine(object): return self.docroutine(*args) + except AttributeError: + pass + if isinstance(object, property): return self.docproperty(*args) + return self.docother(*args) + + def fail(self, object, name=None, *args): + """Raise an exception for unimplemented types.""" + message = "don't know how to document object%s of type %s" % ( + name and ' ' + repr(name), type(object).__name__) + raise TypeError, message + + docmodule = docclass = docroutine = docother = docproperty = docdata = fail + + def getdocloc(self, object): + """Return the location of module docs or None""" + + try: + file = inspect.getabsfile(object) + except TypeError: + file = '(built-in)' + + docloc = os.environ.get("PYTHONDOCS", + "http://www.python.org/doc/current/lib") + basedir = os.path.join(sys.exec_prefix, "lib", + "python"+sys.version[0:3]) + if (isinstance(object, type(os)) and + (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', + 'marshal', 'posix', 'signal', 'sys', + 'thread', 'zipimport') or + (file.startswith(basedir) and + not file.startswith(os.path.join(basedir, 'site-packages'))))): + htmlfile = "module-%s.html" % object.__name__ + if docloc.startswith("http://"): + docloc = "%s/%s" % (docloc.rstrip("/"), htmlfile) + else: + docloc = os.path.join(docloc, htmlfile) + else: + docloc = None + return docloc + +# -------------------------------------------- HTML documentation generator + +class HTMLRepr(Repr): + """Class for safely making an HTML representation of a Python object.""" + def __init__(self): + Repr.__init__(self) + self.maxlist = self.maxtuple = 20 + self.maxdict = 10 + self.maxstring = self.maxother = 100 + + def escape(self, text): + return replace(text, '&', '&', '<', '<', '>', '>') + + def repr(self, object): + return Repr.repr(self, object) + + def repr1(self, x, level): + if hasattr(type(x), '__name__'): + methodname = 'repr_' + join(split(type(x).__name__), '_') + if hasattr(self, methodname): + return getattr(self, methodname)(x, level) + return self.escape(cram(stripid(repr(x)), self.maxother)) + + def repr_string(self, x, level): + test = cram(x, self.maxstring) + testrepr = repr(test) + if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): + # Backslashes are only literal in the string and are never + # needed to make any special characters, so show a raw string. + return 'r' + testrepr[0] + self.escape(test) + testrepr[0] + return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)', + r'<font color="#c040c0">\1</font>', + self.escape(testrepr)) + + repr_str = repr_string + + def repr_instance(self, x, level): + try: + return self.escape(cram(stripid(repr(x)), self.maxstring)) + except: + return self.escape('<%s instance>' % x.__class__.__name__) + + repr_unicode = repr_string + +class HTMLDoc(Doc): + """Formatter class for HTML documentation.""" + + # ------------------------------------------- HTML formatting utilities + + _repr_instance = HTMLRepr() + repr = _repr_instance.repr + escape = _repr_instance.escape + + def page(self, title, contents): + """Format an HTML page.""" + return ''' +<!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> +<html><head><title>Python: %s</title> +</head><body bgcolor="#f0f0f8"> +%s +</body></html>''' % (title, contents) + + def heading(self, title, fgcol, bgcol, extras=''): + """Format a page heading.""" + return ''' +<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading"> +<tr bgcolor="%s"> +<td valign=bottom> <br> +<font color="%s" face="helvetica, arial"> <br>%s</font></td +><td align=right valign=bottom +><font color="%s" face="helvetica, arial">%s</font></td></tr></table> + ''' % (bgcol, fgcol, title, fgcol, extras or ' ') + + def section(self, title, fgcol, bgcol, contents, width=6, + prelude='', marginalia=None, gap=' '): + """Format a section with a heading.""" + if marginalia is None: + marginalia = '<tt>' + ' ' * width + '</tt>' + result = '''<p> +<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> +<tr bgcolor="%s"> +<td colspan=3 valign=bottom> <br> +<font color="%s" face="helvetica, arial">%s</font></td></tr> + ''' % (bgcol, fgcol, title) + if prelude: + result = result + ''' +<tr bgcolor="%s"><td rowspan=2>%s</td> +<td colspan=2>%s</td></tr> +<tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap) + else: + result = result + ''' +<tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap) + + return result + '\n<td width="100%%">%s</td></tr></table>' % contents + + def bigsection(self, title, *args): + """Format a section with a big heading.""" + title = '<big><strong>%s</strong></big>' % title + return self.section(title, *args) + + def preformat(self, text): + """Format literal preformatted text.""" + text = self.escape(expandtabs(text)) + return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', + ' ', ' ', '\n', '<br>\n') + + def multicolumn(self, list, format, cols=4): + """Format a list of items into a multi-column list.""" + result = '' + rows = (len(list)+cols-1)/cols + for col in range(cols): + result = result + '<td width="%d%%" valign=top>' % (100/cols) + for i in range(rows*col, rows*col+rows): + if i < len(list): + result = result + format(list[i]) + '<br>\n' + result = result + '</td>' + return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result + + def grey(self, text): return '<font color="#909090">%s</font>' % text + + def namelink(self, name, *dicts): + """Make a link for an identifier, given name-to-URL mappings.""" + for dict in dicts: + if name in dict: + return '<a href="%s">%s</a>' % (dict[name], name) + return name + + def classlink(self, object, modname): + """Make a link for a class.""" + name, module = object.__name__, sys.modules.get(object.__module__) + if hasattr(module, name) and getattr(module, name) is object: + return '<a href="%s.html#%s">%s</a>' % ( + module.__name__, name, classname(object, modname)) + return classname(object, modname) + + def modulelink(self, object): + """Make a link for a module.""" + return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__) + + def modpkglink(self, (name, path, ispackage, shadowed)): + """Make a link for a module or package to display in an index.""" + if shadowed: + return self.grey(name) + if path: + url = '%s.%s.html' % (path, name) + else: + url = '%s.html' % name + if ispackage: + text = '<strong>%s</strong> (package)' % name + else: + text = name + return '<a href="%s">%s</a>' % (url, text) + + def markup(self, text, escape=None, funcs={}, classes={}, methods={}): + """Mark up some plain text, given a context of symbols to look for. + Each context dictionary maps object names to anchor names.""" + escape = escape or self.escape + results = [] + here = 0 + pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' + r'RFC[- ]?(\d+)|' + r'PEP[- ]?(\d+)|' + r'(self\.)?(\w+))') + while True: + match = pattern.search(text, here) + if not match: break + start, end = match.span() + results.append(escape(text[here:start])) + + all, scheme, rfc, pep, selfdot, name = match.groups() + if scheme: + url = escape(all).replace('"', '"') + results.append('<a href="%s">%s</a>' % (url, url)) + elif rfc: + url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) + results.append('<a href="%s">%s</a>' % (url, escape(all))) + elif pep: + url = 'http://www.python.org/peps/pep-%04d.html' % int(pep) + results.append('<a href="%s">%s</a>' % (url, escape(all))) + elif text[end:end+1] == '(': + results.append(self.namelink(name, methods, funcs, classes)) + elif selfdot: + results.append('self.<strong>%s</strong>' % name) + else: + results.append(self.namelink(name, classes)) + here = end + results.append(escape(text[here:])) + return join(results, '') + + # ---------------------------------------------- type-specific routines + + def formattree(self, tree, modname, parent=None): + """Produce HTML for a class tree as given by inspect.getclasstree().""" + result = '' + for entry in tree: + if type(entry) is type(()): + c, bases = entry + result = result + '<dt><font face="helvetica, arial">' + result = result + self.classlink(c, modname) + if bases and bases != (parent,): + parents = [] + for base in bases: + parents.append(self.classlink(base, modname)) + result = result + '(' + join(parents, ', ') + ')' + result = result + '\n</font></dt>' + elif type(entry) is type([]): + result = result + '<dd>\n%s</dd>\n' % self.formattree( + entry, modname, c) + return '<dl>\n%s</dl>\n' % result + + def docmodule(self, object, name=None, mod=None, *ignored): + """Produce HTML documentation for a module object.""" + name = object.__name__ # ignore the passed-in name + try: + all = object.__all__ + except AttributeError: + all = None + parts = split(name, '.') + links = [] + for i in range(len(parts)-1): + links.append( + '<a href="%s.html"><font color="#ffffff">%s</font></a>' % + (join(parts[:i+1], '.'), parts[i])) + linkedname = join(links + parts[-1:], '.') + head = '<big><big><strong>%s</strong></big></big>' % linkedname + try: + path = inspect.getabsfile(object) + url = path + if sys.platform == 'win32': + import nturl2path + url = nturl2path.pathname2url(path) + filelink = '<a href="file:%s">%s</a>' % (url, path) + except TypeError: + filelink = '(built-in)' + info = [] + if hasattr(object, '__version__'): + version = str(object.__version__) + if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': + version = strip(version[11:-1]) + info.append('version %s' % self.escape(version)) + if hasattr(object, '__date__'): + info.append(self.escape(str(object.__date__))) + if info: + head = head + ' (%s)' % join(info, ', ') + docloc = self.getdocloc(object) + if docloc is not None: + docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals() + else: + docloc = '' + result = self.heading( + head, '#ffffff', '#7799ee', + '<a href=".">index</a><br>' + filelink + docloc) + + modules = inspect.getmembers(object, inspect.ismodule) + + classes, cdict = [], {} + for key, value in inspect.getmembers(object, inspect.isclass): + # if __all__ exists, believe it. Otherwise use old heuristic. + if (all is not None or + (inspect.getmodule(value) or object) is object): + if visiblename(key, all): + classes.append((key, value)) + cdict[key] = cdict[value] = '#' + key + for key, value in classes: + for base in value.__bases__: + key, modname = base.__name__, base.__module__ + module = sys.modules.get(modname) + if modname != name and module and hasattr(module, key): + if getattr(module, key) is base: + if not key in cdict: + cdict[key] = cdict[base] = modname + '.html#' + key + funcs, fdict = [], {} + for key, value in inspect.getmembers(object, inspect.isroutine): + # if __all__ exists, believe it. Otherwise use old heuristic. + if (all is not None or + inspect.isbuiltin(value) or inspect.getmodule(value) is object): + if visiblename(key, all): + funcs.append((key, value)) + fdict[key] = '#-' + key + if inspect.isfunction(value): fdict[value] = fdict[key] + data = [] + for key, value in inspect.getmembers(object, isdata): + if visiblename(key, all): + data.append((key, value)) + + doc = self.markup(getdoc(object), self.preformat, fdict, cdict) + doc = doc and '<tt>%s</tt>' % doc + result = result + '<p>%s</p>\n' % doc + + if hasattr(object, '__path__'): + modpkgs = [] + for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): + modpkgs.append((modname, name, ispkg, 0)) + modpkgs.sort() + contents = self.multicolumn(modpkgs, self.modpkglink) + result = result + self.bigsection( + 'Package Contents', '#ffffff', '#aa55cc', contents) + elif modules: + contents = self.multicolumn( + modules, lambda (key, value), s=self: s.modulelink(value)) + result = result + self.bigsection( + 'Modules', '#fffff', '#aa55cc', contents) + + if classes: + classlist = map(lambda (key, value): value, classes) + contents = [ + self.formattree(inspect.getclasstree(classlist, 1), name)] + for key, value in classes: + contents.append(self.document(value, key, name, fdict, cdict)) + result = result + self.bigsection( + 'Classes', '#ffffff', '#ee77aa', join(contents)) + if funcs: + contents = [] + for key, value in funcs: + contents.append(self.document(value, key, name, fdict, cdict)) + result = result + self.bigsection( + 'Functions', '#ffffff', '#eeaa77', join(contents)) + if data: + contents = [] + for key, value in data: + contents.append(self.document(value, key)) + result = result + self.bigsection( + 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n')) + if hasattr(object, '__author__'): + contents = self.markup(str(object.__author__), self.preformat) + result = result + self.bigsection( + 'Author', '#ffffff', '#7799ee', contents) + if hasattr(object, '__credits__'): + contents = self.markup(str(object.__credits__), self.preformat) + result = result + self.bigsection( + 'Credits', '#ffffff', '#7799ee', contents) + + return result + + def docclass(self, object, name=None, mod=None, funcs={}, classes={}, + *ignored): + """Produce HTML documentation for a class object.""" + realname = object.__name__ + name = name or realname + bases = object.__bases__ + + contents = [] + push = contents.append + + # Cute little class to pump out a horizontal rule between sections. + class HorizontalRule: + def __init__(self): + self.needone = 0 + def maybe(self): + if self.needone: + push('<hr>\n') + self.needone = 1 + hr = HorizontalRule() + + # List the mro, if non-trivial. + mro = deque(inspect.getmro(object)) + if len(mro) > 2: + hr.maybe() + push('<dl><dt>Method resolution order:</dt>\n') + for base in mro: + push('<dd>%s</dd>\n' % self.classlink(base, + object.__module__)) + push('</dl>\n') + + def spill(msg, attrs, predicate): + ok, attrs = _split_list(attrs, predicate) + if ok: + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: + push(self.document(getattr(object, name), name, mod, + funcs, classes, mdict, object)) + push('\n') + return attrs + + def spilldescriptors(msg, attrs, predicate): + ok, attrs = _split_list(attrs, predicate) + if ok: + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: + push(self._docdescriptor(name, value, mod)) + return attrs + + def spilldata(msg, attrs, predicate): + ok, attrs = _split_list(attrs, predicate) + if ok: + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: + base = self.docother(getattr(object, name), name, mod) + if callable(value) or inspect.isdatadescriptor(value): + doc = getattr(value, "__doc__", None) + else: + doc = None + if doc is None: + push('<dl><dt>%s</dl>\n' % base) + else: + doc = self.markup(getdoc(value), self.preformat, + funcs, classes, mdict) + doc = '<dd><tt>%s</tt>' % doc + push('<dl><dt>%s%s</dl>\n' % (base, doc)) + push('\n') + return attrs + + attrs = filter(lambda (name, kind, cls, value): visiblename(name), + classify_class_attrs(object)) + mdict = {} + for key, kind, homecls, value in attrs: + mdict[key] = anchor = '#' + name + '-' + key + value = getattr(object, key) + try: + # The value may not be hashable (e.g., a data attr with + # a dict or list value). + mdict[value] = anchor + except TypeError: + pass + + while attrs: + if mro: + thisclass = mro.popleft() + else: + thisclass = attrs[0][2] + attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) + + if thisclass is __builtin__.object: + attrs = inherited + continue + elif thisclass is object: + tag = 'defined here' + else: + tag = 'inherited from %s' % self.classlink(thisclass, + object.__module__) + tag += ':<br>\n' + + # Sort attrs by name. + try: + attrs.sort(key=lambda t: t[0]) + except TypeError: + attrs.sort(lambda t1, t2: cmp(t1[0], t2[0])) # 2.3 compat + + # Pump out the attrs, segregated by kind. + attrs = spill('Methods %s' % tag, attrs, + lambda t: t[1] == 'method') + attrs = spill('Class methods %s' % tag, attrs, + lambda t: t[1] == 'class method') + attrs = spill('Static methods %s' % tag, attrs, + lambda t: t[1] == 'static method') + attrs = spilldescriptors('Data descriptors %s' % tag, attrs, + lambda t: t[1] == 'data descriptor') + attrs = spilldata('Data and other attributes %s' % tag, attrs, + lambda t: t[1] == 'data') + assert attrs == [] + attrs = inherited + + contents = ''.join(contents) + + if name == realname: + title = '<a name="%s">class <strong>%s</strong></a>' % ( + name, realname) + else: + title = '<strong>%s</strong> = <a name="%s">class %s</a>' % ( + name, name, realname) + if bases: + parents = [] + for base in bases: + parents.append(self.classlink(base, object.__module__)) + title = title + '(%s)' % join(parents, ', ') + doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict) + doc = doc and '<tt>%s<br> </tt>' % doc + + return self.section(title, '#000000', '#ffc8d8', contents, 3, doc) + + def formatvalue(self, object): + """Format an argument default value as text.""" + return self.grey('=' + self.repr(object)) + + def docroutine(self, object, name=None, mod=None, + funcs={}, classes={}, methods={}, cl=None): + """Produce HTML documentation for a function or method object.""" + realname = object.__name__ + name = name or realname + anchor = (cl and cl.__name__ or '') + '-' + name + note = '' + skipdocs = 0 + if inspect.ismethod(object): + imclass = object.im_class + if cl: + if imclass is not cl: + note = ' from ' + self.classlink(imclass, mod) + else: + if object.im_self is not None: + note = ' method of %s instance' % self.classlink( + object.im_self.__class__, mod) + else: + note = ' unbound %s method' % self.classlink(imclass,mod) + object = object.im_func + + if name == realname: + title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname) + else: + if (cl and realname in cl.__dict__ and + cl.__dict__[realname] is object): + reallink = '<a href="#%s">%s</a>' % ( + cl.__name__ + '-' + realname, realname) + skipdocs = 1 + else: + reallink = realname + title = '<a name="%s"><strong>%s</strong></a> = %s' % ( + anchor, name, reallink) + if inspect.isfunction(object): + args, varargs, varkw, defaults = inspect.getargspec(object) + argspec = inspect.formatargspec( + args, varargs, varkw, defaults, formatvalue=self.formatvalue) + if realname == '<lambda>': + title = '<strong>%s</strong> <em>lambda</em> ' % name + argspec = argspec[1:-1] # remove parentheses + else: + argspec = '(...)' + + decl = title + argspec + (note and self.grey( + '<font face="helvetica, arial">%s</font>' % note)) + + if skipdocs: + return '<dl><dt>%s</dt></dl>\n' % decl + else: + doc = self.markup( + getdoc(object), self.preformat, funcs, classes, methods) + doc = doc and '<dd><tt>%s</tt></dd>' % doc + return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc) + + def _docdescriptor(self, name, value, mod): + results = [] + push = results.append + + if name: + push('<dl><dt><strong>%s</strong></dt>\n' % name) + if value.__doc__ is not None: + doc = self.markup(getdoc(value), self.preformat) + push('<dd><tt>%s</tt></dd>\n' % doc) + push('</dl>\n') + + return ''.join(results) + + def docproperty(self, object, name=None, mod=None, cl=None): + """Produce html documentation for a property.""" + return self._docdescriptor(name, object, mod) + + def docother(self, object, name=None, mod=None, *ignored): + """Produce HTML documentation for a data object.""" + lhs = name and '<strong>%s</strong> = ' % name or '' + return lhs + self.repr(object) + + def docdata(self, object, name=None, mod=None, cl=None): + """Produce html documentation for a data descriptor.""" + return self._docdescriptor(name, object, mod) + + def index(self, dir, shadowed=None): + """Generate an HTML index for a directory of modules.""" + modpkgs = [] + if shadowed is None: shadowed = {} + for importer, name, ispkg in pkgutil.iter_modules([dir]): + modpkgs.append((name, '', ispkg, name in shadowed)) + shadowed[name] = 1 + + modpkgs.sort() + contents = self.multicolumn(modpkgs, self.modpkglink) + return self.bigsection(dir, '#ffffff', '#ee77aa', contents) + +# -------------------------------------------- text documentation generator + +class TextRepr(Repr): + """Class for safely making a text representation of a Python object.""" + def __init__(self): + Repr.__init__(self) + self.maxlist = self.maxtuple = 20 + self.maxdict = 10 + self.maxstring = self.maxother = 100 + + def repr1(self, x, level): + if hasattr(type(x), '__name__'): + methodname = 'repr_' + join(split(type(x).__name__), '_') + if hasattr(self, methodname): + return getattr(self, methodname)(x, level) + return cram(stripid(repr(x)), self.maxother) + + def repr_string(self, x, level): + test = cram(x, self.maxstring) + testrepr = repr(test) + if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): + # Backslashes are only literal in the string and are never + # needed to make any special characters, so show a raw string. + return 'r' + testrepr[0] + test + testrepr[0] + return testrepr + + repr_str = repr_string + + def repr_instance(self, x, level): + try: + return cram(stripid(repr(x)), self.maxstring) + except: + return '<%s instance>' % x.__class__.__name__ + +class TextDoc(Doc): + """Formatter class for text documentation.""" + + # ------------------------------------------- text formatting utilities + + _repr_instance = TextRepr() + repr = _repr_instance.repr + + def bold(self, text): + """Format a string in bold by overstriking.""" + return join(map(lambda ch: ch + '\b' + ch, text), '') + + def indent(self, text, prefix=' '): + """Indent text by prepending a given prefix to each line.""" + if not text: return '' + lines = split(text, '\n') + lines = map(lambda line, prefix=prefix: prefix + line, lines) + if lines: lines[-1] = rstrip(lines[-1]) + return join(lines, '\n') + + def section(self, title, contents): + """Format a section with a given heading.""" + return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n' + + # ---------------------------------------------- type-specific routines + + def formattree(self, tree, modname, parent=None, prefix=''): + """Render in text a class tree as returned by inspect.getclasstree().""" + result = '' + for entry in tree: + if type(entry) is type(()): + c, bases = entry + result = result + prefix + classname(c, modname) + if bases and bases != (parent,): + parents = map(lambda c, m=modname: classname(c, m), bases) + result = result + '(%s)' % join(parents, ', ') + result = result + '\n' + elif type(entry) is type([]): + result = result + self.formattree( + entry, modname, c, prefix + ' ') + return result + + def docmodule(self, object, name=None, mod=None): + """Produce text documentation for a given module object.""" + name = object.__name__ # ignore the passed-in name + synop, desc = splitdoc(getdoc(object)) + result = self.section('NAME', name + (synop and ' - ' + synop)) + + try: + all = object.__all__ + except AttributeError: + all = None + + try: + file = inspect.getabsfile(object) + except TypeError: + file = '(built-in)' + result = result + self.section('FILE', file) + + docloc = self.getdocloc(object) + if docloc is not None: + result = result + self.section('MODULE DOCS', docloc) + + if desc: + result = result + self.section('DESCRIPTION', desc) + + classes = [] + for key, value in inspect.getmembers(object, inspect.isclass): + # if __all__ exists, believe it. Otherwise use old heuristic. + if (all is not None + or (inspect.getmodule(value) or object) is object): + if visiblename(key, all): + classes.append((key, value)) + funcs = [] + for key, value in inspect.getmembers(object, inspect.isroutine): + # if __all__ exists, believe it. Otherwise use old heuristic. + if (all is not None or + inspect.isbuiltin(value) or inspect.getmodule(value) is object): + if visiblename(key, all): + funcs.append((key, value)) + data = [] + for key, value in inspect.getmembers(object, isdata): + if visiblename(key, all): + data.append((key, value)) + + if hasattr(object, '__path__'): + modpkgs = [] + for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): + if ispkg: + modpkgs.append(modname + ' (package)') + else: + modpkgs.append(modname) + + modpkgs.sort() + result = result + self.section( + 'PACKAGE CONTENTS', join(modpkgs, '\n')) + + if classes: + classlist = map(lambda (key, value): value, classes) + contents = [self.formattree( + inspect.getclasstree(classlist, 1), name)] + for key, value in classes: + contents.append(self.document(value, key, name)) + result = result + self.section('CLASSES', join(contents, '\n')) + + if funcs: + contents = [] + for key, value in funcs: + contents.append(self.document(value, key, name)) + result = result + self.section('FUNCTIONS', join(contents, '\n')) + + if data: + contents = [] + for key, value in data: + contents.append(self.docother(value, key, name, maxlen=70)) + result = result + self.section('DATA', join(contents, '\n')) + + if hasattr(object, '__version__'): + version = str(object.__version__) + if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': + version = strip(version[11:-1]) + result = result + self.section('VERSION', version) + if hasattr(object, '__date__'): + result = result + self.section('DATE', str(object.__date__)) + if hasattr(object, '__author__'): + result = result + self.section('AUTHOR', str(object.__author__)) + if hasattr(object, '__credits__'): + result = result + self.section('CREDITS', str(object.__credits__)) + return result + + def docclass(self, object, name=None, mod=None): + """Produce text documentation for a given class object.""" + realname = object.__name__ + name = name or realname + bases = object.__bases__ + + def makename(c, m=object.__module__): + return classname(c, m) + + if name == realname: + title = 'class ' + self.bold(realname) + else: + title = self.bold(name) + ' = class ' + realname + if bases: + parents = map(makename, bases) + title = title + '(%s)' % join(parents, ', ') + + doc = getdoc(object) + contents = doc and [doc + '\n'] or [] + push = contents.append + + # List the mro, if non-trivial. + mro = deque(inspect.getmro(object)) + if len(mro) > 2: + push("Method resolution order:") + for base in mro: + push(' ' + makename(base)) + push('') + + # Cute little class to pump out a horizontal rule between sections. + class HorizontalRule: + def __init__(self): + self.needone = 0 + def maybe(self): + if self.needone: + push('-' * 70) + self.needone = 1 + hr = HorizontalRule() + + def spill(msg, attrs, predicate): + ok, attrs = _split_list(attrs, predicate) + if ok: + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: + push(self.document(getattr(object, name), + name, mod, object)) + return attrs + + def spilldescriptors(msg, attrs, predicate): + ok, attrs = _split_list(attrs, predicate) + if ok: + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: + push(self._docdescriptor(name, value, mod)) + return attrs + + def spilldata(msg, attrs, predicate): + ok, attrs = _split_list(attrs, predicate) + if ok: + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: + if callable(value) or inspect.isdatadescriptor(value): + doc = getdoc(value) + else: + doc = None + push(self.docother(getattr(object, name), + name, mod, maxlen=70, doc=doc) + '\n') + return attrs + + attrs = filter(lambda (name, kind, cls, value): visiblename(name), + classify_class_attrs(object)) + while attrs: + if mro: + thisclass = mro.popleft() + else: + thisclass = attrs[0][2] + attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) + + if thisclass is __builtin__.object: + attrs = inherited + continue + elif thisclass is object: + tag = "defined here" + else: + tag = "inherited from %s" % classname(thisclass, + object.__module__) + filter(lambda t: not t[0].startswith('_'), attrs) + + # Sort attrs by name. + attrs.sort() + + # Pump out the attrs, segregated by kind. + attrs = spill("Methods %s:\n" % tag, attrs, + lambda t: t[1] == 'method') + attrs = spill("Class methods %s:\n" % tag, attrs, + lambda t: t[1] == 'class method') + attrs = spill("Static methods %s:\n" % tag, attrs, + lambda t: t[1] == 'static method') + attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs, + lambda t: t[1] == 'data descriptor') + attrs = spilldata("Data and other attributes %s:\n" % tag, attrs, + lambda t: t[1] == 'data') + assert attrs == [] + attrs = inherited + + contents = '\n'.join(contents) + if not contents: + return title + '\n' + return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n' + + def formatvalue(self, object): + """Format an argument default value as text.""" + return '=' + self.repr(object) + + def docroutine(self, object, name=None, mod=None, cl=None): + """Produce text documentation for a function or method object.""" + realname = object.__name__ + name = name or realname + note = '' + skipdocs = 0 + if inspect.ismethod(object): + imclass = object.im_class + if cl: + if imclass is not cl: + note = ' from ' + classname(imclass, mod) + else: + if object.im_self is not None: + note = ' method of %s instance' % classname( + object.im_self.__class__, mod) + else: + note = ' unbound %s method' % classname(imclass,mod) + object = object.im_func + + if name == realname: + title = self.bold(realname) + else: + if (cl and realname in cl.__dict__ and + cl.__dict__[realname] is object): + skipdocs = 1 + title = self.bold(name) + ' = ' + realname + if inspect.isfunction(object): + args, varargs, varkw, defaults = inspect.getargspec(object) + argspec = inspect.formatargspec( + args, varargs, varkw, defaults, formatvalue=self.formatvalue) + if realname == '<lambda>': + title = self.bold(name) + ' lambda ' + argspec = argspec[1:-1] # remove parentheses + else: + argspec = '(...)' + decl = title + argspec + note + + if skipdocs: + return decl + '\n' + else: + doc = getdoc(object) or '' + return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n') + + def _docdescriptor(self, name, value, mod): + results = [] + push = results.append + + if name: + push(self.bold(name)) + push('\n') + doc = getdoc(value) or '' + if doc: + push(self.indent(doc)) + push('\n') + return ''.join(results) + + def docproperty(self, object, name=None, mod=None, cl=None): + """Produce text documentation for a property.""" + return self._docdescriptor(name, object, mod) + + def docdata(self, object, name=None, mod=None, cl=None): + """Produce text documentation for a data descriptor.""" + return self._docdescriptor(name, object, mod) + + def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None): + """Produce text documentation for a data object.""" + repr = self.repr(object) + if maxlen: + line = (name and name + ' = ' or '') + repr + chop = maxlen - len(line) + if chop < 0: repr = repr[:chop] + '...' + line = (name and self.bold(name) + ' = ' or '') + repr + if doc is not None: + line += '\n' + self.indent(str(doc)) + return line + +# --------------------------------------------------------- user interfaces + +def pager(text): + """The first time this is called, determine what kind of pager to use.""" + global pager + pager = getpager() + pager(text) + +def getpager(): + """Decide what method to use for paging through text.""" + if sys.platform.startswith('java'): + return plainpager + if type(sys.stdout) is not types.FileType: + return plainpager + if not sys.stdin.isatty() or not sys.stdout.isatty(): + return plainpager + if 'PAGER' in os.environ: + if sys.platform == 'win32': # pipes completely broken in Windows + return lambda text: tempfilepager(plain(text), os.environ['PAGER']) + elif os.environ.get('TERM') in ('dumb', 'emacs'): + return lambda text: pipepager(plain(text), os.environ['PAGER']) + else: + return lambda text: pipepager(text, os.environ['PAGER']) + if os.environ.get('TERM') in ('dumb', 'emacs'): + return plainpager + if sys.platform == 'win32' or sys.platform.startswith('os2'): + return lambda text: tempfilepager(plain(text), 'more <') + if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: + return lambda text: pipepager(text, 'less') + + import tempfile + (fd, filename) = tempfile.mkstemp() + os.close(fd) + try: + if hasattr(os, 'system') and os.system('more %s' % filename) == 0: + return lambda text: pipepager(text, 'more') + else: + return ttypager + finally: + os.unlink(filename) + +def plain(text): + """Remove boldface formatting from text.""" + return re.sub('.\b', '', text) + +def pipepager(text, cmd): + """Page through text by feeding it to another program.""" + pipe = os.popen(cmd, 'w') + try: + pipe.write(text) + pipe.close() + except IOError: + pass # Ignore broken pipes caused by quitting the pager program. + +def tempfilepager(text, cmd): + """Page through text by invoking a program on a temporary file.""" + import tempfile + filename = tempfile.mktemp() + file = open(filename, 'w') + file.write(text) + file.close() + try: + os.system(cmd + ' ' + filename) + finally: + os.unlink(filename) + +def ttypager(text): + """Page through text on a text terminal.""" + lines = split(plain(text), '\n') + try: + import tty + fd = sys.stdin.fileno() + old = tty.tcgetattr(fd) + tty.setcbreak(fd) + getchar = lambda: sys.stdin.read(1) + except (ImportError, AttributeError): + tty = None + getchar = lambda: sys.stdin.readline()[:-1][:1] + + try: + r = inc = os.environ.get('LINES', 25) - 1 + sys.stdout.write(join(lines[:inc], '\n') + '\n') + while lines[r:]: + sys.stdout.write('-- more --') + sys.stdout.flush() + c = getchar() + + if c in ('q', 'Q'): + sys.stdout.write('\r \r') + break + elif c in ('\r', '\n'): + sys.stdout.write('\r \r' + lines[r] + '\n') + r = r + 1 + continue + if c in ('b', 'B', '\x1b'): + r = r - inc - inc + if r < 0: r = 0 + sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n') + r = r + inc + + finally: + if tty: + tty.tcsetattr(fd, tty.TCSAFLUSH, old) + +def plainpager(text): + """Simply print unformatted text. This is the ultimate fallback.""" + sys.stdout.write(plain(text)) + +def describe(thing): + """Produce a short description of the given thing.""" + if inspect.ismodule(thing): + if thing.__name__ in sys.builtin_module_names: + return 'built-in module ' + thing.__name__ + if hasattr(thing, '__path__'): + return 'package ' + thing.__name__ + else: + return 'module ' + thing.__name__ + if inspect.isbuiltin(thing): + return 'built-in function ' + thing.__name__ + if inspect.isgetsetdescriptor(thing): + return 'getset descriptor %s.%s.%s' % ( + thing.__objclass__.__module__, thing.__objclass__.__name__, + thing.__name__) + if inspect.ismemberdescriptor(thing): + return 'member descriptor %s.%s.%s' % ( + thing.__objclass__.__module__, thing.__objclass__.__name__, + thing.__name__) + if inspect.isclass(thing): + return 'class ' + thing.__name__ + if inspect.isfunction(thing): + return 'function ' + thing.__name__ + if insp... [truncated message content] |
From: <fwi...@us...> - 2008-11-23 14:16:40
|
Revision: 5614 http://jython.svn.sourceforge.net/jython/?rev=5614&view=rev Author: fwierzbicki Date: 2008-11-23 14:16:31 +0000 (Sun, 23 Nov 2008) Log Message: ----------- Removed merge tracking for "svnmerge" for https://jython.svn.sourceforge.net/svnroot/jython/branches/nowalker Property Changed: ---------------- branches/astwrite/ Property changes on: branches/astwrite ___________________________________________________________________ Modified: svnmerge-integrated - /branches/nowalker:1-5263 /trunk/jython:1-5584 + /trunk/jython:1-5584 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-11-23 14:15:01
|
Revision: 5613 http://jython.svn.sourceforge.net/jython/?rev=5613&view=rev Author: fwierzbicki Date: 2008-11-23 14:14:52 +0000 (Sun, 23 Nov 2008) Log Message: ----------- Initialized merge tracking via "svnmerge" with revisions "1-5584" from https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython Property Changed: ---------------- branches/astwrite/ Property changes on: branches/astwrite ___________________________________________________________________ Modified: svnmerge-integrated - /branches/nowalker:1-5263 + /branches/nowalker:1-5263 /trunk/jython:1-5584 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-11-23 14:01:11
|
Revision: 5612 http://jython.svn.sourceforge.net/jython/?rev=5612&view=rev Author: fwierzbicki Date: 2008-11-23 14:01:06 +0000 (Sun, 23 Nov 2008) Log Message: ----------- set* that take lists now take objects in prep for converting from Python objects. Modified Paths: -------------- branches/astwrite/ast/asdl_antlr.py branches/astwrite/src/org/python/antlr/ast/Assert.java branches/astwrite/src/org/python/antlr/ast/Assign.java branches/astwrite/src/org/python/antlr/ast/Attribute.java branches/astwrite/src/org/python/antlr/ast/AugAssign.java branches/astwrite/src/org/python/antlr/ast/BinOp.java branches/astwrite/src/org/python/antlr/ast/BoolOp.java branches/astwrite/src/org/python/antlr/ast/Break.java branches/astwrite/src/org/python/antlr/ast/Call.java branches/astwrite/src/org/python/antlr/ast/ClassDef.java branches/astwrite/src/org/python/antlr/ast/Compare.java branches/astwrite/src/org/python/antlr/ast/Continue.java branches/astwrite/src/org/python/antlr/ast/Delete.java branches/astwrite/src/org/python/antlr/ast/Dict.java branches/astwrite/src/org/python/antlr/ast/Ellipsis.java branches/astwrite/src/org/python/antlr/ast/Exec.java branches/astwrite/src/org/python/antlr/ast/Expr.java branches/astwrite/src/org/python/antlr/ast/Expression.java branches/astwrite/src/org/python/antlr/ast/ExtSlice.java branches/astwrite/src/org/python/antlr/ast/For.java branches/astwrite/src/org/python/antlr/ast/FunctionDef.java branches/astwrite/src/org/python/antlr/ast/GeneratorExp.java branches/astwrite/src/org/python/antlr/ast/Global.java branches/astwrite/src/org/python/antlr/ast/If.java branches/astwrite/src/org/python/antlr/ast/IfExp.java branches/astwrite/src/org/python/antlr/ast/Import.java branches/astwrite/src/org/python/antlr/ast/ImportFrom.java branches/astwrite/src/org/python/antlr/ast/Index.java branches/astwrite/src/org/python/antlr/ast/Interactive.java branches/astwrite/src/org/python/antlr/ast/Lambda.java branches/astwrite/src/org/python/antlr/ast/List.java branches/astwrite/src/org/python/antlr/ast/ListComp.java branches/astwrite/src/org/python/antlr/ast/Module.java branches/astwrite/src/org/python/antlr/ast/Name.java branches/astwrite/src/org/python/antlr/ast/Num.java branches/astwrite/src/org/python/antlr/ast/Pass.java branches/astwrite/src/org/python/antlr/ast/Print.java branches/astwrite/src/org/python/antlr/ast/Raise.java branches/astwrite/src/org/python/antlr/ast/Repr.java branches/astwrite/src/org/python/antlr/ast/Return.java branches/astwrite/src/org/python/antlr/ast/Slice.java branches/astwrite/src/org/python/antlr/ast/Str.java branches/astwrite/src/org/python/antlr/ast/Subscript.java branches/astwrite/src/org/python/antlr/ast/Suite.java branches/astwrite/src/org/python/antlr/ast/TryExcept.java branches/astwrite/src/org/python/antlr/ast/TryFinally.java branches/astwrite/src/org/python/antlr/ast/Tuple.java branches/astwrite/src/org/python/antlr/ast/UnaryOp.java branches/astwrite/src/org/python/antlr/ast/While.java branches/astwrite/src/org/python/antlr/ast/With.java branches/astwrite/src/org/python/antlr/ast/Yield.java branches/astwrite/src/org/python/antlr/ast/aliasType.java branches/astwrite/src/org/python/antlr/ast/argumentsType.java branches/astwrite/src/org/python/antlr/ast/comprehensionType.java branches/astwrite/src/org/python/antlr/ast/excepthandlerType.java branches/astwrite/src/org/python/antlr/ast/keywordType.java Modified: branches/astwrite/ast/asdl_antlr.py =================================================================== --- branches/astwrite/ast/asdl_antlr.py 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/ast/asdl_antlr.py 2008-11-23 14:01:06 UTC (rev 5612) @@ -413,19 +413,22 @@ str(field.name).capitalize()), depth) self.emit("return %s;" % field.name, depth+1) self.emit("}", depth) - self.emit("public void set%s(%s) {" % (str(field.name).capitalize(), - self.fieldDef(field)), depth) + self.emit("public Object get%s() {" % (str(field.name).capitalize()), depth) + self.emit("return %s;" % field.name, depth+1) + self.emit("}", depth) + self.emit("public void set%s(Object %s) {" % (str(field.name).capitalize(), + field.name), depth) if field.seq: - self.emit("this.%s = new %s(%s);" % (field.name, - self.javaType(field, True), field.name), depth+1) + self.emit("this.%s = new %s(" % (field.name, self.javaType(field, True)), depth+1) + self.emit("(%s)%s);" % (self.javaType(field), field.name), depth+2) else: - self.emit("this.%s = %s;" % (field.name, field.name), depth+1) + self.emit("this.%s = (%s)%s;" % (field.name, self.javaType(field), field.name), depth+1) self.emit("}", depth) self.emit("", 0) bltinnames = { - 'int' : 'int', - 'bool' : 'boolean', + 'int' : 'Integer', + 'bool' : 'Boolean', 'identifier' : 'String', 'string' : 'Object', 'object' : 'Object', # was PyObject Modified: branches/astwrite/src/org/python/antlr/ast/Assert.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Assert.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Assert.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,17 +12,23 @@ public exprType getInternalTest() { return test; } - public void setTest(exprType test) { - this.test = test; + public Object getTest() { + return test; } + public void setTest(Object test) { + this.test = (exprType)test; + } private exprType msg; public exprType getInternalMsg() { return msg; } - public void setMsg(exprType msg) { - this.msg = msg; + public Object getMsg() { + return msg; } + public void setMsg(Object msg) { + this.msg = (exprType)msg; + } private final static String[] fields = new String[] {"test", "msg"}; @@ -43,7 +49,7 @@ addChild(msg); } - public Assert(int ttype, Token token, exprType test, exprType msg) { + public Assert(Integer ttype, Token token, exprType test, exprType msg) { super(ttype, token); this.test = test; addChild(test); Modified: branches/astwrite/src/org/python/antlr/ast/Assign.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Assign.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Assign.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,17 +12,24 @@ public ListWrapper<exprType> getInternalTargets() { return targets; } - public void setTargets(java.util.List<exprType> targets) { - this.targets = new ListWrapper<exprType>(targets); + public Object getTargets() { + return targets; } + public void setTargets(Object targets) { + this.targets = new ListWrapper<exprType>( + (java.util.List<exprType>)targets); + } private exprType value; public exprType getInternalValue() { return value; } - public void setValue(exprType value) { - this.value = value; + public Object getValue() { + return value; } + public void setValue(Object value) { + this.value = (exprType)value; + } private final static String[] fields = new String[] {"targets", "value"}; @@ -52,7 +59,7 @@ addChild(value); } - public Assign(int ttype, Token token, java.util.List<exprType> targets, + public Assign(Integer ttype, Token token, java.util.List<exprType> targets, exprType value) { super(ttype, token); this.targets = new ListWrapper<exprType>(targets); Modified: branches/astwrite/src/org/python/antlr/ast/Attribute.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Attribute.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Attribute.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,25 +12,34 @@ public exprType getInternalValue() { return value; } - public void setValue(exprType value) { - this.value = value; + public Object getValue() { + return value; } + public void setValue(Object value) { + this.value = (exprType)value; + } private String attr; public String getInternalAttr() { return attr; } - public void setAttr(String attr) { - this.attr = attr; + public Object getAttr() { + return attr; } + public void setAttr(Object attr) { + this.attr = (String)attr; + } private expr_contextType ctx; public expr_contextType getInternalCtx() { return ctx; } - public void setCtx(expr_contextType ctx) { - this.ctx = ctx; + public Object getCtx() { + return ctx; } + public void setCtx(Object ctx) { + this.ctx = (expr_contextType)ctx; + } private final static String[] fields = new String[] {"value", "attr", @@ -53,7 +62,7 @@ this.ctx = ctx; } - public Attribute(int ttype, Token token, exprType value, String attr, + public Attribute(Integer ttype, Token token, exprType value, String attr, expr_contextType ctx) { super(ttype, token); this.value = value; Modified: branches/astwrite/src/org/python/antlr/ast/AugAssign.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/AugAssign.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/AugAssign.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,25 +12,34 @@ public exprType getInternalTarget() { return target; } - public void setTarget(exprType target) { - this.target = target; + public Object getTarget() { + return target; } + public void setTarget(Object target) { + this.target = (exprType)target; + } private operatorType op; public operatorType getInternalOp() { return op; } - public void setOp(operatorType op) { - this.op = op; + public Object getOp() { + return op; } + public void setOp(Object op) { + this.op = (operatorType)op; + } private exprType value; public exprType getInternalValue() { return value; } - public void setValue(exprType value) { - this.value = value; + public Object getValue() { + return value; } + public void setValue(Object value) { + this.value = (exprType)value; + } private final static String[] fields = new String[] {"target", "op", @@ -55,8 +64,8 @@ addChild(value); } - public AugAssign(int ttype, Token token, exprType target, operatorType op, - exprType value) { + public AugAssign(Integer ttype, Token token, exprType target, operatorType + op, exprType value) { super(ttype, token); this.target = target; addChild(target); Modified: branches/astwrite/src/org/python/antlr/ast/BinOp.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/BinOp.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/BinOp.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -2,6 +2,7 @@ package org.python.antlr.ast; import org.python.antlr.PythonTree; import org.python.antlr.ListWrapper; +import org.python.core.PyInteger; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; import java.io.DataOutputStream; @@ -12,27 +13,44 @@ public exprType getInternalLeft() { return left; } - public void setLeft(exprType left) { - this.left = left; + public Object getLeft() { + return left; } + public void setLeft(Object left) { + if (left instanceof exprType) { + this.left = (exprType)left; + } else if (left instanceof Integer) { + this.left = new Num(new PyInteger((Integer)left)); + } + } + private operatorType op; public operatorType getInternalOp() { return op; } - public void setOp(operatorType op) { - this.op = op; + public Object getOp() { + return op; } + public void setOp(Object op) { + this.op = (operatorType)op; + } private exprType right; public exprType getInternalRight() { return right; } - public void setRight(exprType right) { - this.right = right; + public Object getRight() { + return right; } + public void setRight(Object right) { + if (right instanceof exprType) { + this.right = (exprType)right; + } else if (right instanceof Integer) { + this.right = new Num(new PyInteger((Integer)right)); + } + } - private final static String[] fields = new String[] {"left", "op", "right"}; public String[] get_fields() { return fields; } @@ -44,6 +62,15 @@ addChild(right); } + public BinOp() { + } + + public BinOp(Object left, operatorType op, Object right) { + setLeft(left); + setOp(op); + setRight(right); + } + public BinOp(Token token, exprType left, operatorType op, exprType right) { super(token); this.left = left; @@ -53,7 +80,7 @@ addChild(right); } - public BinOp(int ttype, Token token, exprType left, operatorType op, + public BinOp(Integer ttype, Token token, exprType left, operatorType op, exprType right) { super(ttype, token); this.left = left; Modified: branches/astwrite/src/org/python/antlr/ast/BoolOp.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/BoolOp.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/BoolOp.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,17 +12,24 @@ public boolopType getInternalOp() { return op; } - public void setOp(boolopType op) { - this.op = op; + public Object getOp() { + return op; } + public void setOp(Object op) { + this.op = (boolopType)op; + } private ListWrapper<exprType> values; public ListWrapper<exprType> getInternalValues() { return values; } - public void setValues(java.util.List<exprType> values) { - this.values = new ListWrapper<exprType>(values); + public Object getValues() { + return values; } + public void setValues(Object values) { + this.values = new ListWrapper<exprType>( + (java.util.List<exprType>)values); + } private final static String[] fields = new String[] {"op", "values"}; @@ -49,7 +56,7 @@ } } - public BoolOp(int ttype, Token token, boolopType op, + public BoolOp(Integer ttype, Token token, boolopType op, java.util.List<exprType> values) { super(ttype, token); this.op = op; Modified: branches/astwrite/src/org/python/antlr/ast/Break.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Break.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Break.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -16,7 +16,7 @@ super(token); } - public Break(int ttype, Token token) { + public Break(Integer ttype, Token token) { super(ttype, token); } Modified: branches/astwrite/src/org/python/antlr/ast/Call.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Call.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Call.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,41 +12,58 @@ public exprType getInternalFunc() { return func; } - public void setFunc(exprType func) { - this.func = func; + public Object getFunc() { + return func; } + public void setFunc(Object func) { + this.func = (exprType)func; + } private ListWrapper<exprType> args; public ListWrapper<exprType> getInternalArgs() { return args; } - public void setArgs(java.util.List<exprType> args) { - this.args = new ListWrapper<exprType>(args); + public Object getArgs() { + return args; } + public void setArgs(Object args) { + this.args = new ListWrapper<exprType>( + (java.util.List<exprType>)args); + } private ListWrapper<keywordType> keywords; public ListWrapper<keywordType> getInternalKeywords() { return keywords; } - public void setKeywords(java.util.List<keywordType> keywords) { - this.keywords = new ListWrapper<keywordType>(keywords); + public Object getKeywords() { + return keywords; } + public void setKeywords(Object keywords) { + this.keywords = new ListWrapper<keywordType>( + (java.util.List<keywordType>)keywords); + } private exprType starargs; public exprType getInternalStarargs() { return starargs; } - public void setStarargs(exprType starargs) { - this.starargs = starargs; + public Object getStarargs() { + return starargs; } + public void setStarargs(Object starargs) { + this.starargs = (exprType)starargs; + } private exprType kwargs; public exprType getInternalKwargs() { return kwargs; } - public void setKwargs(exprType kwargs) { - this.kwargs = kwargs; + public Object getKwargs() { + return kwargs; } + public void setKwargs(Object kwargs) { + this.kwargs = (exprType)kwargs; + } private final static String[] fields = new String[] {"func", "args", @@ -99,9 +116,9 @@ addChild(kwargs); } - public Call(int ttype, Token token, exprType func, java.util.List<exprType> - args, java.util.List<keywordType> keywords, exprType starargs, exprType - kwargs) { + public Call(Integer ttype, Token token, exprType func, + java.util.List<exprType> args, java.util.List<keywordType> keywords, + exprType starargs, exprType kwargs) { super(ttype, token); this.func = func; addChild(func); Modified: branches/astwrite/src/org/python/antlr/ast/ClassDef.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/ClassDef.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/ClassDef.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,33 +12,48 @@ public String getInternalName() { return name; } - public void setName(String name) { - this.name = name; + public Object getName() { + return name; } + public void setName(Object name) { + this.name = (String)name; + } private ListWrapper<exprType> bases; public ListWrapper<exprType> getInternalBases() { return bases; } - public void setBases(java.util.List<exprType> bases) { - this.bases = new ListWrapper<exprType>(bases); + public Object getBases() { + return bases; } + public void setBases(Object bases) { + this.bases = new ListWrapper<exprType>( + (java.util.List<exprType>)bases); + } private ListWrapper<stmtType> body; public ListWrapper<stmtType> getInternalBody() { return body; } - public void setBody(java.util.List<stmtType> body) { - this.body = new ListWrapper<stmtType>(body); + public Object getBody() { + return body; } + public void setBody(Object body) { + this.body = new ListWrapper<stmtType>( + (java.util.List<stmtType>)body); + } private ListWrapper<exprType> decorators; public ListWrapper<exprType> getInternalDecorators() { return decorators; } - public void setDecorators(java.util.List<exprType> decorators) { - this.decorators = new ListWrapper<exprType>(decorators); + public Object getDecorators() { + return decorators; } + public void setDecorators(Object decorators) { + this.decorators = new ListWrapper<exprType>( + (java.util.List<exprType>)decorators); + } private final static String[] fields = new String[] {"name", "bases", @@ -92,7 +107,7 @@ } } - public ClassDef(int ttype, Token token, String name, + public ClassDef(Integer ttype, Token token, String name, java.util.List<exprType> bases, java.util.List<stmtType> body, java.util.List<exprType> decorators) { super(ttype, token); Modified: branches/astwrite/src/org/python/antlr/ast/Compare.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Compare.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Compare.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,25 +12,36 @@ public exprType getInternalLeft() { return left; } - public void setLeft(exprType left) { - this.left = left; + public Object getLeft() { + return left; } + public void setLeft(Object left) { + this.left = (exprType)left; + } private ListWrapper<cmpopType> ops; public ListWrapper<cmpopType> getInternalOps() { return ops; } - public void setOps(java.util.List<cmpopType> ops) { - this.ops = new ListWrapper<cmpopType>(ops); + public Object getOps() { + return ops; } + public void setOps(Object ops) { + this.ops = new ListWrapper<cmpopType>( + (java.util.List<cmpopType>)ops); + } private ListWrapper<exprType> comparators; public ListWrapper<exprType> getInternalComparators() { return comparators; } - public void setComparators(java.util.List<exprType> comparators) { - this.comparators = new ListWrapper<exprType>(comparators); + public Object getComparators() { + return comparators; } + public void setComparators(Object comparators) { + this.comparators = new ListWrapper<exprType>( + (java.util.List<exprType>)comparators); + } private final static String[] fields = new String[] {"left", "ops", @@ -64,7 +75,7 @@ } } - public Compare(int ttype, Token token, exprType left, + public Compare(Integer ttype, Token token, exprType left, java.util.List<cmpopType> ops, java.util.List<exprType> comparators) { super(ttype, token); this.left = left; Modified: branches/astwrite/src/org/python/antlr/ast/Continue.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Continue.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Continue.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -16,7 +16,7 @@ super(token); } - public Continue(int ttype, Token token) { + public Continue(Integer ttype, Token token) { super(ttype, token); } Modified: branches/astwrite/src/org/python/antlr/ast/Delete.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Delete.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Delete.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,9 +12,13 @@ public ListWrapper<exprType> getInternalTargets() { return targets; } - public void setTargets(java.util.List<exprType> targets) { - this.targets = new ListWrapper<exprType>(targets); + public Object getTargets() { + return targets; } + public void setTargets(Object targets) { + this.targets = new ListWrapper<exprType>( + (java.util.List<exprType>)targets); + } private final static String[] fields = new String[] {"targets"}; @@ -39,7 +43,8 @@ } } - public Delete(int ttype, Token token, java.util.List<exprType> targets) { + public Delete(Integer ttype, Token token, java.util.List<exprType> targets) + { super(ttype, token); this.targets = new ListWrapper<exprType>(targets); if (targets != null) { Modified: branches/astwrite/src/org/python/antlr/ast/Dict.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Dict.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Dict.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,17 +12,25 @@ public ListWrapper<exprType> getInternalKeys() { return keys; } - public void setKeys(java.util.List<exprType> keys) { - this.keys = new ListWrapper<exprType>(keys); + public Object getKeys() { + return keys; } + public void setKeys(Object keys) { + this.keys = new ListWrapper<exprType>( + (java.util.List<exprType>)keys); + } private ListWrapper<exprType> values; public ListWrapper<exprType> getInternalValues() { return values; } - public void setValues(java.util.List<exprType> values) { - this.values = new ListWrapper<exprType>(values); + public Object getValues() { + return values; } + public void setValues(Object values) { + this.values = new ListWrapper<exprType>( + (java.util.List<exprType>)values); + } private final static String[] fields = new String[] {"keys", "values"}; @@ -61,7 +69,7 @@ } } - public Dict(int ttype, Token token, java.util.List<exprType> keys, + public Dict(Integer ttype, Token token, java.util.List<exprType> keys, java.util.List<exprType> values) { super(ttype, token); this.keys = new ListWrapper<exprType>(keys); Modified: branches/astwrite/src/org/python/antlr/ast/Ellipsis.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Ellipsis.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Ellipsis.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -16,7 +16,7 @@ super(token); } - public Ellipsis(int ttype, Token token) { + public Ellipsis(Integer ttype, Token token) { super(ttype, token); } Modified: branches/astwrite/src/org/python/antlr/ast/Exec.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Exec.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Exec.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,25 +12,34 @@ public exprType getInternalBody() { return body; } - public void setBody(exprType body) { - this.body = body; + public Object getBody() { + return body; } + public void setBody(Object body) { + this.body = (exprType)body; + } private exprType globals; public exprType getInternalGlobals() { return globals; } - public void setGlobals(exprType globals) { - this.globals = globals; + public Object getGlobals() { + return globals; } + public void setGlobals(Object globals) { + this.globals = (exprType)globals; + } private exprType locals; public exprType getInternalLocals() { return locals; } - public void setLocals(exprType locals) { - this.locals = locals; + public Object getLocals() { + return locals; } + public void setLocals(Object locals) { + this.locals = (exprType)locals; + } private final static String[] fields = new String[] {"body", "globals", @@ -56,7 +65,7 @@ addChild(locals); } - public Exec(int ttype, Token token, exprType body, exprType globals, + public Exec(Integer ttype, Token token, exprType body, exprType globals, exprType locals) { super(ttype, token); this.body = body; Modified: branches/astwrite/src/org/python/antlr/ast/Expr.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Expr.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Expr.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,9 +12,12 @@ public exprType getInternalValue() { return value; } - public void setValue(exprType value) { - this.value = value; + public Object getValue() { + return value; } + public void setValue(Object value) { + this.value = (exprType)value; + } private final static String[] fields = new String[] {"value"}; @@ -31,7 +34,7 @@ addChild(value); } - public Expr(int ttype, Token token, exprType value) { + public Expr(Integer ttype, Token token, exprType value) { super(ttype, token); this.value = value; addChild(value); Modified: branches/astwrite/src/org/python/antlr/ast/Expression.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Expression.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Expression.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,9 +12,12 @@ public exprType getInternalBody() { return body; } - public void setBody(exprType body) { - this.body = body; + public Object getBody() { + return body; } + public void setBody(Object body) { + this.body = (exprType)body; + } private final static String[] fields = new String[] {"body"}; @@ -31,7 +34,7 @@ addChild(body); } - public Expression(int ttype, Token token, exprType body) { + public Expression(Integer ttype, Token token, exprType body) { super(ttype, token); this.body = body; addChild(body); Modified: branches/astwrite/src/org/python/antlr/ast/ExtSlice.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/ExtSlice.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/ExtSlice.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,9 +12,13 @@ public ListWrapper<sliceType> getInternalDims() { return dims; } - public void setDims(java.util.List<sliceType> dims) { - this.dims = new ListWrapper<sliceType>(dims); + public Object getDims() { + return dims; } + public void setDims(Object dims) { + this.dims = new ListWrapper<sliceType>( + (java.util.List<sliceType>)dims); + } private final static String[] fields = new String[] {"dims"}; @@ -39,7 +43,8 @@ } } - public ExtSlice(int ttype, Token token, java.util.List<sliceType> dims) { + public ExtSlice(Integer ttype, Token token, java.util.List<sliceType> dims) + { super(ttype, token); this.dims = new ListWrapper<sliceType>(dims); if (dims != null) { Modified: branches/astwrite/src/org/python/antlr/ast/For.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/For.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/For.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,33 +12,47 @@ public exprType getInternalTarget() { return target; } - public void setTarget(exprType target) { - this.target = target; + public Object getTarget() { + return target; } + public void setTarget(Object target) { + this.target = (exprType)target; + } private exprType iter; public exprType getInternalIter() { return iter; } - public void setIter(exprType iter) { - this.iter = iter; + public Object getIter() { + return iter; } + public void setIter(Object iter) { + this.iter = (exprType)iter; + } private ListWrapper<stmtType> body; public ListWrapper<stmtType> getInternalBody() { return body; } - public void setBody(java.util.List<stmtType> body) { - this.body = new ListWrapper<stmtType>(body); + public Object getBody() { + return body; } + public void setBody(Object body) { + this.body = new ListWrapper<stmtType>( + (java.util.List<stmtType>)body); + } private ListWrapper<stmtType> orelse; public ListWrapper<stmtType> getInternalOrelse() { return orelse; } - public void setOrelse(java.util.List<stmtType> orelse) { - this.orelse = new ListWrapper<stmtType>(orelse); + public Object getOrelse() { + return orelse; } + public void setOrelse(Object orelse) { + this.orelse = new ListWrapper<stmtType>( + (java.util.List<stmtType>)orelse); + } private final static String[] fields = new String[] {"target", "iter", @@ -86,7 +100,7 @@ } } - public For(int ttype, Token token, exprType target, exprType iter, + public For(Integer ttype, Token token, exprType target, exprType iter, java.util.List<stmtType> body, java.util.List<stmtType> orelse) { super(ttype, token); this.target = target; Modified: branches/astwrite/src/org/python/antlr/ast/FunctionDef.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/FunctionDef.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/FunctionDef.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,33 +12,47 @@ public String getInternalName() { return name; } - public void setName(String name) { - this.name = name; + public Object getName() { + return name; } + public void setName(Object name) { + this.name = (String)name; + } private argumentsType args; public argumentsType getInternalArgs() { return args; } - public void setArgs(argumentsType args) { - this.args = args; + public Object getArgs() { + return args; } + public void setArgs(Object args) { + this.args = (argumentsType)args; + } private ListWrapper<stmtType> body; public ListWrapper<stmtType> getInternalBody() { return body; } - public void setBody(java.util.List<stmtType> body) { - this.body = new ListWrapper<stmtType>(body); + public Object getBody() { + return body; } + public void setBody(Object body) { + this.body = new ListWrapper<stmtType>( + (java.util.List<stmtType>)body); + } private ListWrapper<exprType> decorators; public ListWrapper<exprType> getInternalDecorators() { return decorators; } - public void setDecorators(java.util.List<exprType> decorators) { - this.decorators = new ListWrapper<exprType>(decorators); + public Object getDecorators() { + return decorators; } + public void setDecorators(Object decorators) { + this.decorators = new ListWrapper<exprType>( + (java.util.List<exprType>)decorators); + } private final static String[] fields = new String[] {"name", "args", @@ -82,8 +96,8 @@ } } - public FunctionDef(int ttype, Token token, String name, argumentsType args, - java.util.List<stmtType> body, java.util.List<exprType> decorators) { + public FunctionDef(Integer ttype, Token token, String name, argumentsType + args, java.util.List<stmtType> body, java.util.List<exprType> decorators) { super(ttype, token); this.name = name; this.args = args; Modified: branches/astwrite/src/org/python/antlr/ast/GeneratorExp.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/GeneratorExp.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/GeneratorExp.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,17 +12,24 @@ public exprType getInternalElt() { return elt; } - public void setElt(exprType elt) { - this.elt = elt; + public Object getElt() { + return elt; } + public void setElt(Object elt) { + this.elt = (exprType)elt; + } private ListWrapper<comprehensionType> generators; public ListWrapper<comprehensionType> getInternalGenerators() { return generators; } - public void setGenerators(java.util.List<comprehensionType> generators) { - this.generators = new ListWrapper<comprehensionType>(generators); + public Object getGenerators() { + return generators; } + public void setGenerators(Object generators) { + this.generators = new ListWrapper<comprehensionType>( + (java.util.List<comprehensionType>)generators); + } private final static String[] fields = new String[] {"elt", "generators"}; @@ -53,7 +60,7 @@ } } - public GeneratorExp(int ttype, Token token, exprType elt, + public GeneratorExp(Integer ttype, Token token, exprType elt, java.util.List<comprehensionType> generators) { super(ttype, token); this.elt = elt; Modified: branches/astwrite/src/org/python/antlr/ast/Global.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Global.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Global.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,9 +12,13 @@ public ListWrapper<String> getInternalNames() { return names; } - public void setNames(java.util.List<String> names) { - this.names = new ListWrapper<String>(names); + public Object getNames() { + return names; } + public void setNames(Object names) { + this.names = new ListWrapper<String>( + (java.util.List<String>)names); + } private final static String[] fields = new String[] {"names"}; @@ -29,7 +33,7 @@ this.names = new ListWrapper<String>(names); } - public Global(int ttype, Token token, java.util.List<String> names) { + public Global(Integer ttype, Token token, java.util.List<String> names) { super(ttype, token); this.names = new ListWrapper<String>(names); } Modified: branches/astwrite/src/org/python/antlr/ast/If.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/If.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/If.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,25 +12,36 @@ public exprType getInternalTest() { return test; } - public void setTest(exprType test) { - this.test = test; + public Object getTest() { + return test; } + public void setTest(Object test) { + this.test = (exprType)test; + } private ListWrapper<stmtType> body; public ListWrapper<stmtType> getInternalBody() { return body; } - public void setBody(java.util.List<stmtType> body) { - this.body = new ListWrapper<stmtType>(body); + public Object getBody() { + return body; } + public void setBody(Object body) { + this.body = new ListWrapper<stmtType>( + (java.util.List<stmtType>)body); + } private ListWrapper<stmtType> orelse; public ListWrapper<stmtType> getInternalOrelse() { return orelse; } - public void setOrelse(java.util.List<stmtType> orelse) { - this.orelse = new ListWrapper<stmtType>(orelse); + public Object getOrelse() { + return orelse; } + public void setOrelse(Object orelse) { + this.orelse = new ListWrapper<stmtType>( + (java.util.List<stmtType>)orelse); + } private final static String[] fields = new String[] {"test", "body", @@ -74,8 +85,8 @@ } } - public If(int ttype, Token token, exprType test, java.util.List<stmtType> - body, java.util.List<stmtType> orelse) { + public If(Integer ttype, Token token, exprType test, + java.util.List<stmtType> body, java.util.List<stmtType> orelse) { super(ttype, token); this.test = test; addChild(test); Modified: branches/astwrite/src/org/python/antlr/ast/IfExp.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/IfExp.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/IfExp.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,25 +12,34 @@ public exprType getInternalTest() { return test; } - public void setTest(exprType test) { - this.test = test; + public Object getTest() { + return test; } + public void setTest(Object test) { + this.test = (exprType)test; + } private exprType body; public exprType getInternalBody() { return body; } - public void setBody(exprType body) { - this.body = body; + public Object getBody() { + return body; } + public void setBody(Object body) { + this.body = (exprType)body; + } private exprType orelse; public exprType getInternalOrelse() { return orelse; } - public void setOrelse(exprType orelse) { - this.orelse = orelse; + public Object getOrelse() { + return orelse; } + public void setOrelse(Object orelse) { + this.orelse = (exprType)orelse; + } private final static String[] fields = new String[] {"test", "body", @@ -56,8 +65,8 @@ addChild(orelse); } - public IfExp(int ttype, Token token, exprType test, exprType body, exprType - orelse) { + public IfExp(Integer ttype, Token token, exprType test, exprType body, + exprType orelse) { super(ttype, token); this.test = test; addChild(test); Modified: branches/astwrite/src/org/python/antlr/ast/Import.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Import.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Import.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,9 +12,13 @@ public ListWrapper<aliasType> getInternalNames() { return names; } - public void setNames(java.util.List<aliasType> names) { - this.names = new ListWrapper<aliasType>(names); + public Object getNames() { + return names; } + public void setNames(Object names) { + this.names = new ListWrapper<aliasType>( + (java.util.List<aliasType>)names); + } private final static String[] fields = new String[] {"names"}; @@ -39,7 +43,7 @@ } } - public Import(int ttype, Token token, java.util.List<aliasType> names) { + public Import(Integer ttype, Token token, java.util.List<aliasType> names) { super(ttype, token); this.names = new ListWrapper<aliasType>(names); if (names != null) { Modified: branches/astwrite/src/org/python/antlr/ast/ImportFrom.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/ImportFrom.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/ImportFrom.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,32 +12,42 @@ public String getInternalModule() { return module; } - public void setModule(String module) { - this.module = module; + public Object getModule() { + return module; } + public void setModule(Object module) { + this.module = (String)module; + } private ListWrapper<aliasType> names; public ListWrapper<aliasType> getInternalNames() { return names; } - public void setNames(java.util.List<aliasType> names) { - this.names = new ListWrapper<aliasType>(names); + public Object getNames() { + return names; } + public void setNames(Object names) { + this.names = new ListWrapper<aliasType>( + (java.util.List<aliasType>)names); + } - private int level; - public int getInternalLevel() { + private Integer level; + public Integer getInternalLevel() { return level; } - public void setLevel(int level) { - this.level = level; + public Object getLevel() { + return level; } + public void setLevel(Object level) { + this.level = (Integer)level; + } private final static String[] fields = new String[] {"module", "names", "level"}; public String[] get_fields() { return fields; } - public ImportFrom(String module, java.util.List<aliasType> names, int + public ImportFrom(String module, java.util.List<aliasType> names, Integer level) { this.module = module; this.names = new ListWrapper<aliasType>(names); @@ -50,7 +60,7 @@ } public ImportFrom(Token token, String module, java.util.List<aliasType> - names, int level) { + names, Integer level) { super(token); this.module = module; this.names = new ListWrapper<aliasType>(names); @@ -62,8 +72,8 @@ this.level = level; } - public ImportFrom(int ttype, Token token, String module, - java.util.List<aliasType> names, int level) { + public ImportFrom(Integer ttype, Token token, String module, + java.util.List<aliasType> names, Integer level) { super(ttype, token); this.module = module; this.names = new ListWrapper<aliasType>(names); @@ -76,7 +86,7 @@ } public ImportFrom(PythonTree tree, String module, java.util.List<aliasType> - names, int level) { + names, Integer level) { super(tree); this.module = module; this.names = new ListWrapper<aliasType>(names); Modified: branches/astwrite/src/org/python/antlr/ast/Index.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Index.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Index.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,9 +12,12 @@ public exprType getInternalValue() { return value; } - public void setValue(exprType value) { - this.value = value; + public Object getValue() { + return value; } + public void setValue(Object value) { + this.value = (exprType)value; + } private final static String[] fields = new String[] {"value"}; @@ -31,7 +34,7 @@ addChild(value); } - public Index(int ttype, Token token, exprType value) { + public Index(Integer ttype, Token token, exprType value) { super(ttype, token); this.value = value; addChild(value); Modified: branches/astwrite/src/org/python/antlr/ast/Interactive.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Interactive.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Interactive.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,9 +12,13 @@ public ListWrapper<stmtType> getInternalBody() { return body; } - public void setBody(java.util.List<stmtType> body) { - this.body = new ListWrapper<stmtType>(body); + public Object getBody() { + return body; } + public void setBody(Object body) { + this.body = new ListWrapper<stmtType>( + (java.util.List<stmtType>)body); + } private final static String[] fields = new String[] {"body"}; @@ -39,7 +43,8 @@ } } - public Interactive(int ttype, Token token, java.util.List<stmtType> body) { + public Interactive(Integer ttype, Token token, java.util.List<stmtType> + body) { super(ttype, token); this.body = new ListWrapper<stmtType>(body); if (body != null) { Modified: branches/astwrite/src/org/python/antlr/ast/Lambda.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Lambda.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Lambda.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,17 +12,23 @@ public argumentsType getInternalArgs() { return args; } - public void setArgs(argumentsType args) { - this.args = args; + public Object getArgs() { + return args; } + public void setArgs(Object args) { + this.args = (argumentsType)args; + } private exprType body; public exprType getInternalBody() { return body; } - public void setBody(exprType body) { - this.body = body; + public Object getBody() { + return body; } + public void setBody(Object body) { + this.body = (exprType)body; + } private final static String[] fields = new String[] {"args", "body"}; @@ -41,7 +47,8 @@ addChild(body); } - public Lambda(int ttype, Token token, argumentsType args, exprType body) { + public Lambda(Integer ttype, Token token, argumentsType args, exprType + body) { super(ttype, token); this.args = args; this.body = body; Modified: branches/astwrite/src/org/python/antlr/ast/List.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/List.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/List.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,17 +12,24 @@ public ListWrapper<exprType> getInternalElts() { return elts; } - public void setElts(java.util.List<exprType> elts) { - this.elts = new ListWrapper<exprType>(elts); + public Object getElts() { + return elts; } + public void setElts(Object elts) { + this.elts = new ListWrapper<exprType>( + (java.util.List<exprType>)elts); + } private expr_contextType ctx; public expr_contextType getInternalCtx() { return ctx; } - public void setCtx(expr_contextType ctx) { - this.ctx = ctx; + public Object getCtx() { + return ctx; } + public void setCtx(Object ctx) { + this.ctx = (expr_contextType)ctx; + } private final static String[] fields = new String[] {"elts", "ctx"}; @@ -50,7 +57,7 @@ this.ctx = ctx; } - public List(int ttype, Token token, java.util.List<exprType> elts, + public List(Integer ttype, Token token, java.util.List<exprType> elts, expr_contextType ctx) { super(ttype, token); this.elts = new ListWrapper<exprType>(elts); Modified: branches/astwrite/src/org/python/antlr/ast/ListComp.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/ListComp.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/ListComp.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,17 +12,24 @@ public exprType getInternalElt() { return elt; } - public void setElt(exprType elt) { - this.elt = elt; + public Object getElt() { + return elt; } + public void setElt(Object elt) { + this.elt = (exprType)elt; + } private ListWrapper<comprehensionType> generators; public ListWrapper<comprehensionType> getInternalGenerators() { return generators; } - public void setGenerators(java.util.List<comprehensionType> generators) { - this.generators = new ListWrapper<comprehensionType>(generators); + public Object getGenerators() { + return generators; } + public void setGenerators(Object generators) { + this.generators = new ListWrapper<comprehensionType>( + (java.util.List<comprehensionType>)generators); + } private final static String[] fields = new String[] {"elt", "generators"}; @@ -53,7 +60,7 @@ } } - public ListComp(int ttype, Token token, exprType elt, + public ListComp(Integer ttype, Token token, exprType elt, java.util.List<comprehensionType> generators) { super(ttype, token); this.elt = elt; Modified: branches/astwrite/src/org/python/antlr/ast/Module.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Module.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Module.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,9 +12,13 @@ public ListWrapper<stmtType> getInternalBody() { return body; } - public void setBody(java.util.List<stmtType> body) { - this.body = new ListWrapper<stmtType>(body); + public Object getBody() { + return body; } + public void setBody(Object body) { + this.body = new ListWrapper<stmtType>( + (java.util.List<stmtType>)body); + } private final static String[] fields = new String[] {"body"}; @@ -39,7 +43,7 @@ } } - public Module(int ttype, Token token, java.util.List<stmtType> body) { + public Module(Integer ttype, Token token, java.util.List<stmtType> body) { super(ttype, token); this.body = new ListWrapper<stmtType>(body); if (body != null) { Modified: branches/astwrite/src/org/python/antlr/ast/Name.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Name.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Name.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,17 +12,23 @@ public String getInternalId() { return id; } - public void setId(String id) { - this.id = id; + public Object getId() { + return id; } + public void setId(Object id) { + this.id = (String)id; + } private expr_contextType ctx; public expr_contextType getInternalCtx() { return ctx; } - public void setCtx(expr_contextType ctx) { - this.ctx = ctx; + public Object getCtx() { + return ctx; } + public void setCtx(Object ctx) { + this.ctx = (expr_contextType)ctx; + } private final static String[] fields = new String[] {"id", "ctx"}; @@ -39,7 +45,7 @@ this.ctx = ctx; } - public Name(int ttype, Token token, String id, expr_contextType ctx) { + public Name(Integer ttype, Token token, String id, expr_contextType ctx) { super(ttype, token); this.id = id; this.ctx = ctx; Modified: branches/astwrite/src/org/python/antlr/ast/Num.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Num.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Num.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,8 +12,11 @@ public Object getInternalN() { return n; } + public Object getN() { + return n; + } public void setN(Object n) { - this.n = n; + this.n = (Object)n; } @@ -29,7 +32,7 @@ this.n = n; } - public Num(int ttype, Token token, Object n) { + public Num(Integer ttype, Token token, Object n) { super(ttype, token); this.n = n; } Modified: branches/astwrite/src/org/python/antlr/ast/Pass.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Pass.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Pass.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -16,7 +16,7 @@ super(token); } - public Pass(int ttype, Token token) { + public Pass(Integer ttype, Token token) { super(ttype, token); } Modified: branches/astwrite/src/org/python/antlr/ast/Print.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Print.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Print.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,32 +12,42 @@ public exprType getInternalDest() { return dest; } - public void setDest(exprType dest) { - this.dest = dest; + public Object getDest() { + return dest; } + public void setDest(Object dest) { + this.dest = (exprType)dest; + } private ListWrapper<exprType> values; public ListWrapper<exprType> getInternalValues() { return values; } - public void setValues(java.util.List<exprType> values) { - this.values = new ListWrapper<exprType>(values); + public Object getValues() { + return values; } + public void setValues(Object values) { + this.values = new ListWrapper<exprType>( + (java.util.List<exprType>)values); + } - private boolean nl; - public boolean getInternalNl() { + private Boolean nl; + public Boolean getInternalNl() { return nl; } - public void setNl(boolean nl) { - this.nl = nl; + public Object getNl() { + return nl; } + public void setNl(Object nl) { + this.nl = (Boolean)nl; + } private final static String[] fields = new String[] {"dest", "values", "nl"}; public String[] get_fields() { return fields; } - public Print(exprType dest, java.util.List<exprType> values, boolean nl) { + public Print(exprType dest, java.util.List<exprType> values, Boolean nl) { this.dest = dest; addChild(dest); this.values = new ListWrapper<exprType>(values); @@ -50,7 +60,7 @@ } public Print(Token token, exprType dest, java.util.List<exprType> values, - boolean nl) { + Boolean nl) { super(token); this.dest = dest; addChild(dest); @@ -63,8 +73,8 @@ this.nl = nl; } - public Print(int ttype, Token token, exprType dest, - java.util.List<exprType> values, boolean nl) { + public Print(Integer ttype, Token token, exprType dest, + java.util.List<exprType> values, Boolean nl) { super(ttype, token); this.dest = dest; addChild(dest); @@ -78,7 +88,7 @@ } public Print(PythonTree tree, exprType dest, java.util.List<exprType> - values, boolean nl) { + values, Boolean nl) { super(tree); this.dest = dest; addChild(dest); Modified: branches/astwrite/src/org/python/antlr/ast/Raise.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Raise.java 2008-11-23 06:28:45 UTC (rev 5611) +++ branches/astwrite/src/org/python/antlr/ast/Raise.java 2008-11-23 14:01:06 UTC (rev 5612) @@ -12,25 +12,34 @@ public exprType getInternalExcepttype() { return excepttype; } - public void setExcepttype(exprType excepttype) { - this.excepttype = excepttype; + public Object getExcepttype() { + return excepttype; } + public void setExcepttype(Object excepttype) { + this.excepttype = (exprType)excepttype; + } private exprType inst; public exprType getInternalInst() { return inst; } - public void setInst(exprType inst) { - this.inst = inst; + public Object getInst() { + return inst; } + public void setInst(Object inst) { + this.inst = (exprType)inst; + } private exprType tback; public exprType getInternalTback() ... [truncated message content] |
From: <pj...@us...> - 2008-11-23 06:28:46
|
Revision: 5611 http://jython.svn.sourceforge.net/jython/?rev=5611&view=rev Author: pjenvey Date: 2008-11-23 06:28:45 +0000 (Sun, 23 Nov 2008) Log Message: ----------- fix the Carlo Verre hack because open builtin classes are only cool in Ruby and JavaScript, or something like that fixes #1058 and test_descr.carloverre Modified Paths: -------------- trunk/jython/Lib/test/test_descr.py trunk/jython/src/org/python/core/PyObject.java Modified: trunk/jython/Lib/test/test_descr.py =================================================================== --- trunk/jython/Lib/test/test_descr.py 2008-11-23 04:35:59 UTC (rev 5610) +++ trunk/jython/Lib/test/test_descr.py 2008-11-23 06:28:45 UTC (rev 5611) @@ -4424,9 +4424,6 @@ # Lack __basicsize__: http://bugs.jython.org/issue1017 slotmultipleinheritance, - # Carlo hacked us: http://bugs.jython.org/issue1058 - carloverre, - # Jython lacks CPython method-wrappers (though maybe this # should pass anyway?) methodwrapper, Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2008-11-23 04:35:59 UTC (rev 5610) +++ trunk/jython/src/org/python/core/PyObject.java 2008-11-23 06:28:45 UTC (rev 5611) @@ -3591,6 +3591,7 @@ @ExposedMethod final void object___setattr__(PyObject name, PyObject value) { + hackCheck("__setattr__"); object___setattr__(asName(name), value); } @@ -3626,6 +3627,7 @@ @ExposedMethod final void object___delattr__(PyObject name) { + hackCheck("__delattr__"); object___delattr__(asName(name)); } @@ -3675,6 +3677,19 @@ } /** + * Helper to check for object.__setattr__ or __delattr__ applied to a type (The Carlo + * Verre hack). + * + * @param what String method name to check for + */ + private void hackCheck(String what) { + if (this instanceof PyType && ((PyType)this).builtin) { + throw Py.TypeError(String.format("can't apply this %s to %s object", what, + objtype.fastGetName())); + } + } + + /** * Used for pickling. Default implementation calls object___reduce__. * * @return a tuple of (class, tuple) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-23 04:36:05
|
Revision: 5610 http://jython.svn.sourceforge.net/jython/?rev=5610&view=rev Author: pjenvey Date: 2008-11-23 04:35:59 +0000 (Sun, 23 Nov 2008) Log Message: ----------- zlib docs fixes #1798554, #1798556 thanks ukeshav Modified Paths: -------------- trunk/jython/Lib/zlib.py Modified: trunk/jython/Lib/zlib.py =================================================================== --- trunk/jython/Lib/zlib.py 2008-11-23 04:18:48 UTC (rev 5609) +++ trunk/jython/Lib/zlib.py 2008-11-23 04:35:59 UTC (rev 5610) @@ -1,3 +1,18 @@ +""" +The functions in this module allow compression and decompression using the +zlib library, which is based on GNU zip. + +adler32(string[, start]) -- Compute an Adler-32 checksum. +compress(string[, level]) -- Compress string, with compression level in 1-9. +compressobj([level]) -- Return a compressor object. +crc32(string[, start]) -- Compute a CRC-32 checksum. +decompress(string,[wbits],[bufsize]) -- Decompresses a compressed string. +decompressobj([wbits]) -- Return a decompressor object. + +'wbits' is window buffer size. +Compressor objects support compress() and flush() methods; decompressor +objects support decompress() and flush(). +""" import jarray, binascii from java.util.zip import Adler32, Deflater, Inflater This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-23 04:18:54
|
Revision: 5609 http://jython.svn.sourceforge.net/jython/?rev=5609&view=rev Author: pjenvey Date: 2008-11-23 04:18:48 +0000 (Sun, 23 Nov 2008) Log Message: ----------- ((PyInteger)obj.__int__()).getValue() -> obj.asInt() to avoid potential ClassCastException mayhem now that __int__ can return longs. as a side effect TypeErrors are raised on conversion failure rather than AttributeErrors (which is usually more appropriate anyway) fixes #1052 Modified Paths: -------------- trunk/jython/src/com/ziclix/python/sql/Fetch.java trunk/jython/src/com/ziclix/python/sql/Procedure.java trunk/jython/src/com/ziclix/python/sql/PyCursor.java trunk/jython/src/com/ziclix/python/sql/PyStatement.java trunk/jython/src/org/python/core/PyArray.java trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/modules/imp.java trunk/jython/src/org/python/modules/struct.java trunk/jython/src/org/python/modules/thread/thread.java trunk/jython/src/org/python/modules/time/Time.java Modified: trunk/jython/src/com/ziclix/python/sql/Fetch.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/Fetch.java 2008-11-23 04:15:40 UTC (rev 5608) +++ trunk/jython/src/com/ziclix/python/sql/Fetch.java 2008-11-23 04:18:48 UTC (rev 5609) @@ -304,7 +304,7 @@ for (int i = 0, len = procedure.columns.__len__(); i < len; i++) { PyObject column = procedure.columns.__getitem__(i); - int colType = ((PyInteger)column.__getitem__(Procedure.COLUMN_TYPE).__int__()).getValue(); + int colType = column.__getitem__(Procedure.COLUMN_TYPE).asInt(); switch (colType) { @@ -316,7 +316,7 @@ a[2] = Py.newInteger(-1); a[3] = column.__getitem__(Procedure.LENGTH); - switch (((PyInteger)a[1].__int__()).getValue()) { + switch (a[1].asInt()) { case Types.BIGINT: case Types.BIT: @@ -335,7 +335,7 @@ break; } - int nullable = ((PyInteger)column.__getitem__(Procedure.NULLABLE).__int__()).getValue(); + int nullable = column.__getitem__(Procedure.NULLABLE).asInt(); a[6] = (nullable == DatabaseMetaData.procedureNullable) ? Py.One : Py.Zero; @@ -363,8 +363,8 @@ for (int i = 0, j = 0, len = procedure.columns.__len__(); i < len; i++) { PyObject obj = Py.None; PyObject column = procedure.columns.__getitem__(i); - int colType = ((PyInteger)column.__getitem__(Procedure.COLUMN_TYPE).__int__()).getValue(); - int dataType = ((PyInteger)column.__getitem__(Procedure.DATA_TYPE).__int__()).getValue(); + int colType = column.__getitem__(Procedure.COLUMN_TYPE).asInt(); + int dataType = column.__getitem__(Procedure.DATA_TYPE).asInt(); switch (colType) { Modified: trunk/jython/src/com/ziclix/python/sql/Procedure.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/Procedure.java 2008-11-23 04:15:40 UTC (rev 5608) +++ trunk/jython/src/com/ziclix/python/sql/Procedure.java 2008-11-23 04:18:48 UTC (rev 5609) @@ -165,8 +165,8 @@ if (normal) { statement = cursor.connection.connection.prepareCall(sqlString); } else { - int t = ((PyInteger)rsType.__int__()).getValue(); - int c = ((PyInteger)rsConcur.__int__()).getValue(); + int t = rsType.asInt(); + int c = rsConcur.asInt(); statement = cursor.connection.connection.prepareCall(sqlString, t, c); } @@ -202,7 +202,7 @@ // do nothing with params at the moment for (int i = 0, len = this.columns.__len__(), binding = 0; i < len; i++) { PyObject column = this.columns.__getitem__(i); - int colType = ((PyInteger)column.__getitem__(COLUMN_TYPE).__int__()).getValue(); + int colType = column.__getitem__(COLUMN_TYPE).asInt(); switch (colType) { @@ -213,7 +213,7 @@ PyInteger key = Py.newInteger(binding++); if (bindings.__finditem__(key) == null) { - int dataType = ((PyInteger)column.__getitem__(DATA_TYPE).__int__()).getValue(); + int dataType = column.__getitem__(DATA_TYPE).asInt(); bindings.__setitem__(key, Py.newInteger(dataType)); } @@ -256,7 +256,7 @@ if (this.columns != Py.None) { for (int i = 0, len = this.columns.__len__(); i < len; i++) { PyObject column = this.columns.__getitem__(i); - int colType = ((PyInteger)column.__getitem__(COLUMN_TYPE).__int__()).getValue(); + int colType = column.__getitem__(COLUMN_TYPE).asInt(); switch (colType) { @@ -326,8 +326,8 @@ for (int i = 0, len = this.columns.__len__(); i < len; i++) { PyObject column = this.columns.__getitem__(i); - int colType = ((PyInteger)column.__getitem__(COLUMN_TYPE).__int__()).getValue(); - int dataType = ((PyInteger)column.__getitem__(DATA_TYPE).__int__()).getValue(); + int colType = column.__getitem__(COLUMN_TYPE).asInt(); + int dataType = column.__getitem__(DATA_TYPE).asInt(); String dataTypeName = column.__getitem__(DATA_TYPE_NAME).toString(); switch (colType) { Modified: trunk/jython/src/com/ziclix/python/sql/PyCursor.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyCursor.java 2008-11-23 04:15:40 UTC (rev 5608) +++ trunk/jython/src/com/ziclix/python/sql/PyCursor.java 2008-11-23 04:18:48 UTC (rev 5609) @@ -180,9 +180,9 @@ public void __setattr__(String name, PyObject value) { if ("arraysize".equals(name)) { - this.arraysize = ((PyInteger)value.__int__()).getValue(); + this.arraysize = value.asInt(); } else if ("softspace".equals(name)) { - this.softspace = ((PyInteger)value.__int__()).getValue(); + this.softspace = value.asInt(); } else if ("datahandler".equals(name)) { this.datahandler = (DataHandler)value.__tojava__(DataHandler.class); } else { @@ -398,8 +398,8 @@ sqlStatement = this.connection.connection.createStatement(); } } else { - int t = ((PyInteger)this.rsType.__int__()).getValue(); - int c = ((PyInteger)this.rsConcur.__int__()).getValue(); + int t = this.rsType.asInt(); + int c = this.rsConcur.asInt(); if (prepared) { sqlStatement = this.connection.connection.prepareStatement(sqlString, t, c); @@ -414,7 +414,7 @@ } if (maxRows != Py.None) { - stmt.statement.setMaxRows(((PyInteger)maxRows.__int__()).getValue()); + stmt.statement.setMaxRows(maxRows.asInt()); } } catch (AbstractMethodError e) { throw zxJDBC.makeException(zxJDBC.NotSupportedError, zxJDBC.getString("nodynamiccursors")); @@ -457,7 +457,7 @@ Statement stmt = procedure.prepareCall(this.rsType, this.rsConcur); if (maxRows != Py.None) { - stmt.setMaxRows(((PyInteger)maxRows.__int__()).getValue()); + stmt.setMaxRows(maxRows.asInt()); } // get the bindings per the stored proc spec @@ -897,7 +897,7 @@ PyCursor cursor = (PyCursor)__self__; switch (index) { case 0 : - return cursor.fetchmany(((PyInteger)arg.__int__()).getValue()); + return cursor.fetchmany(arg.asInt()); case 5 : cursor.execute(arg, Py.None, Py.None, Py.None); return Py.None; @@ -911,7 +911,7 @@ cursor.executemany(arg, Py.None, Py.None, Py.None); return Py.None; case 10 : - cursor.scroll(((PyInteger)arg.__int__()).getValue(), "relative"); + cursor.scroll(arg.asInt(), "relative"); return Py.None; case 11 : cursor.execute(arg, Py.None, Py.None, Py.None); @@ -938,7 +938,7 @@ cursor.executemany(arga, argb, Py.None, Py.None); return Py.None; case 10 : - cursor.scroll(((PyInteger)arga.__int__()).getValue(), argb.toString()); + cursor.scroll(arga.asInt(), argb.toString()); return Py.None; default : throw info.unexpectedCall(2, false); Modified: trunk/jython/src/com/ziclix/python/sql/PyStatement.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyStatement.java 2008-11-23 04:15:40 UTC (rev 5608) +++ trunk/jython/src/com/ziclix/python/sql/PyStatement.java 2008-11-23 04:18:48 UTC (rev 5609) @@ -300,7 +300,7 @@ if (binding != null) { try { - int bindingValue = ((PyInteger)binding.__int__()).getValue(); + int bindingValue = binding.asInt(); datahandler.setJDBCObject(preparedStatement, column, param, bindingValue); } catch (PyException e) { Modified: trunk/jython/src/org/python/core/PyArray.java =================================================================== --- trunk/jython/src/org/python/core/PyArray.java 2008-11-23 04:15:40 UTC (rev 5608) +++ trunk/jython/src/org/python/core/PyArray.java 2008-11-23 04:18:48 UTC (rev 5609) @@ -438,7 +438,7 @@ return s.toString().charAt(0); } else if (obj.__nonzero__()) { - return ((PyInteger)obj.__int__()).getValue(); + return obj.asInt(); } else { return -1; Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2008-11-23 04:15:40 UTC (rev 5608) +++ trunk/jython/src/org/python/core/PyString.java 2008-11-23 04:18:48 UTC (rev 5609) @@ -2953,7 +2953,9 @@ } int val; try { - val = ((PyInteger)arg.__int__()).getValue(); + // Explicitly __int__ so we can look for an AttributeError (which is + // less invasive to mask than a TypeError) + val = arg.__int__().asInt(); } catch (PyException e){ if (Py.matchException(e, Py.AttributeError)) { throw Py.TypeError("%c requires int or char"); Modified: trunk/jython/src/org/python/modules/imp.java =================================================================== --- trunk/jython/src/org/python/modules/imp.java 2008-11-23 04:15:40 UTC (rev 5608) +++ trunk/jython/src/org/python/modules/imp.java 2008-11-23 04:18:48 UTC (rev 5609) @@ -180,7 +180,7 @@ public static PyObject load_module(String name, PyObject file, PyObject filename, PyTuple data) { PyObject mod = Py.None; PySystemState sys = Py.getSystemState(); - int type = ((PyInteger)data.__getitem__(2).__int__()).getValue(); + int type = data.__getitem__(2).asInt(); while(mod == Py.None) { Object o = file.__tojava__(InputStream.class); if (o == Py.NoConversion) { Modified: trunk/jython/src/org/python/modules/struct.java =================================================================== --- trunk/jython/src/org/python/modules/struct.java 2008-11-23 04:15:40 UTC (rev 5608) +++ trunk/jython/src/org/python/modules/struct.java 2008-11-23 04:18:48 UTC (rev 5609) @@ -329,7 +329,7 @@ int get_int(PyObject value) { try { - return ((PyInteger)value.__int__()).getValue(); + return value.asInt(); } catch (PyException ex) { throw StructError("required argument is not an integer"); } Modified: trunk/jython/src/org/python/modules/thread/thread.java =================================================================== --- trunk/jython/src/org/python/modules/thread/thread.java 2008-11-23 04:15:40 UTC (rev 5608) +++ trunk/jython/src/org/python/modules/thread/thread.java 2008-11-23 04:18:48 UTC (rev 5609) @@ -101,7 +101,7 @@ return stack_size; case 1: long old_stack_size = stack_size; - int proposed_stack_size = ((PyInteger)args[0].__int__()).getValue(); + int proposed_stack_size = args[0].asInt(); if (proposed_stack_size != 0 && proposed_stack_size < 32768) { // as specified by Python, Java quietly ignores what // it considers are too small Modified: trunk/jython/src/org/python/modules/time/Time.java =================================================================== --- trunk/jython/src/org/python/modules/time/Time.java 2008-11-23 04:15:40 UTC (rev 5608) +++ trunk/jython/src/org/python/modules/time/Time.java 2008-11-23 04:18:48 UTC (rev 5609) @@ -154,7 +154,7 @@ private static int item(PyTuple tup, int i) { // knows about and asserts format on tuple items. See // documentation for Python's time module for details. - int val = ((PyInteger)tup.__getitem__(i).__int__()).getValue(); + int val = tup.__getitem__(i).asInt(); boolean valid = true; switch (i) { case 0: break; // year This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-23 04:15:49
|
Revision: 5608 http://jython.svn.sourceforge.net/jython/?rev=5608&view=rev Author: pjenvey Date: 2008-11-23 04:15:40 +0000 (Sun, 23 Nov 2008) Log Message: ----------- relax struct_time entry types to PyObject, CPython allows non ints here. mostly to get rid of __int__ calls w/ a PyInteger cast refs #1052 Modified Paths: -------------- trunk/jython/src/org/python/modules/time/PyTimeTuple.java Modified: trunk/jython/src/org/python/modules/time/PyTimeTuple.java =================================================================== --- trunk/jython/src/org/python/modules/time/PyTimeTuple.java 2008-11-23 02:36:05 UTC (rev 5607) +++ trunk/jython/src/org/python/modules/time/PyTimeTuple.java 2008-11-23 04:15:40 UTC (rev 5608) @@ -24,7 +24,7 @@ public class PyTimeTuple extends PyTuple { @ExposedGet - public PyInteger tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst; + public PyObject tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst; @ExposedGet public final int n_sequence_fields = 9, n_fields = 9, n_unnamed_fields = 0; @@ -33,15 +33,15 @@ PyTimeTuple(PyObject... vals) { super(TYPE, vals); - tm_year = (PyInteger)vals[0].__int__(); - tm_mon = (PyInteger)vals[1].__int__(); - tm_mday = (PyInteger)vals[2].__int__(); - tm_hour = (PyInteger)vals[3].__int__(); - tm_min = (PyInteger)vals[4].__int__(); - tm_sec = (PyInteger)vals[5].__int__();; - tm_wday = (PyInteger)vals[6].__int__();; - tm_yday = (PyInteger)vals[7].__int__();; - tm_isdst =(PyInteger)vals[8].__int__();; + tm_year = vals[0]; + tm_mon = vals[1]; + tm_mday = vals[2]; + tm_hour = vals[3]; + tm_min = vals[4]; + tm_sec = vals[5]; + tm_wday = vals[6]; + tm_yday = vals[7]; + tm_isdst =vals[8]; } @ExposedNew This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-23 02:36:12
|
Revision: 5607 http://jython.svn.sourceforge.net/jython/?rev=5607&view=rev Author: cgroves Date: 2008-11-23 02:36:05 +0000 (Sun, 23 Nov 2008) Log Message: ----------- Rip out PyJavaClass and friends. This isn't even close to passing regrtest, but it runs well enough to start the interpreter and get through the first few. Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/IdImpl.java branches/newstyle-java-types/src/org/python/core/Py.java branches/newstyle-java-types/src/org/python/core/PyBeanEventProperty.java branches/newstyle-java-types/src/org/python/core/PyClass.java branches/newstyle-java-types/src/org/python/core/PyFile.java branches/newstyle-java-types/src/org/python/core/PyInstance.java branches/newstyle-java-types/src/org/python/core/PyJavaPackage.java branches/newstyle-java-types/src/org/python/core/PyObject.java branches/newstyle-java-types/src/org/python/core/PyReflectedConstructor.java branches/newstyle-java-types/src/org/python/core/PyType.java branches/newstyle-java-types/src/org/python/core/StdoutWrapper.java branches/newstyle-java-types/src/org/python/core/__builtin__.java branches/newstyle-java-types/src/org/python/core/imp.java branches/newstyle-java-types/src/org/python/modules/cPickle.java branches/newstyle-java-types/src/org/python/modules/cStringIO.java Removed Paths: ------------- branches/newstyle-java-types/Lib/jreload.py branches/newstyle-java-types/Lib/jxxload_help/ branches/newstyle-java-types/src/org/python/core/AutoInternalTables.java branches/newstyle-java-types/src/org/python/core/CollectionProxy.java branches/newstyle-java-types/src/org/python/core/InternalTables.java branches/newstyle-java-types/src/org/python/core/PyJavaClass.java branches/newstyle-java-types/src/org/python/core/PyJavaInnerClass.java branches/newstyle-java-types/src/org/python/core/PyJavaInstance.java branches/newstyle-java-types/src/org/python/core/SoftIInternalTables.java branches/newstyle-java-types/src/org/python/core/WeakInternalTables.java branches/newstyle-java-types/src/org/python/modules/_jython.java Deleted: branches/newstyle-java-types/Lib/jreload.py =================================================================== --- branches/newstyle-java-types/Lib/jreload.py 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/Lib/jreload.py 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,119 +0,0 @@ -# java classes reload support (experimental) -# Copyright 2000 Samuele Pedroni - -# ?? could have problem with import pkg.jclass.inner (this should not be used in any case) -# ?? using import * with a load-set together with reloading can be confusing -# cannot be fixed => anyway import * is not for production code - -__version__ = "0.3" - -import sys -from org.python.core import imp,PyJavaPackage,PyJavaClass -from _jython import is_lazy as _is_lazy - -import jxxload_help - - -class _LoaderFactory(jxxload_help.JavaLoaderFactory): - def __init__(self,path): - vfs = jxxload_help.PathVFS() - for fname in path: - vfs.addVFS(fname) - self.vfs = vfs - - def makeLoader(self): - return jxxload_help.PathVFSJavaLoader(self.vfs,imp.getSyspathJavaLoader()) - -class _Unload: - - def __init__(self,ls): - self.ls = ls - self.ls_name = ls._name - self.loader = ls._mgr.loader - - def do_unload(self,pkg): - for n in pkg.__dict__.keys(): - e = pkg.__dict__[n] - if isinstance(e,PyJavaClass): - if _is_lazy(e): continue - if e.classLoader is self.loader: - del pkg.__dict__[n] - if pkg.__name__: - n = self.ls_name + '.' + pkg.__name__ + '.' +n - else: - n = self.ls_name + '.' + n - if sys.modules.has_key(n): del sys.modules[n] - - elif isinstance(e,PyJavaPackage): - self.do_unload(e) - - def __call__(self): - if self.loader: - if self.ls._mgr.checkLoader() is self.loader: - self.do_unload(self.ls._top) - self.ls._mgr.resetLoader() - loader = self.loader - jxxload_help.DiscardHelp.discard(loader,loader.interfaces) - self.loader = None - -class LoadSet: -# ?? for the moment from import * and dir do not work for LoadSet, but work for -# contained pkgs -# need java impl as PyObject - - def __init__(self,name,path): - mgr = jxxload_help.PackageManager(path,_LoaderFactory(path)) - self._name = name - self._mgr = mgr - self._top = mgr.topLevelPackage - - def __getattr__(self,name): - try: - return getattr(self._top,name) - except: - if name == 'unload': return _Unload(self) - raise - - - def __repr__(self): - return "<java load-set %s>" % self._name - -def unloadf(ls): - if not isinstance(ls,LoadSet): raise TypeError,"unloadf(): arg is not a load-set" - return _Unload(ls) - -def makeLoadSet(name,path): - if sys.modules.has_key(name): return sys.modules[name] - sys.modules[name] = ls = LoadSet(name,path) - return ls - -_reload = reload - -def _do_reload(ls_name,mgr,pkg): - pkg_name = pkg.__name__ - for n in pkg.__dict__.keys(): - e = pkg.__dict__[n] - if isinstance(e,PyJavaClass): - if _is_lazy(e): continue - del pkg.__dict__[n] - try : - c = mgr.findClass(pkg_name,n); - if c: - pkg.__dict__[n] = c - if pkg_name: - n = ls_name + '.' + pkg_name + '.' + n - else: - n = ls_name + '.' + n - if sys.modules.has_key(n): sys.modules[n] = c - except: - pass - elif isinstance(e,PyJavaPackage): - _do_reload(ls_name,mgr,e) - -def reload(ls): - if isinstance(ls,LoadSet): - ls._mgr.resetLoader() - _do_reload(ls._name,ls._mgr,ls._top) - return ls - else: - return _reload(ls) Deleted: branches/newstyle-java-types/src/org/python/core/AutoInternalTables.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/AutoInternalTables.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/AutoInternalTables.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,155 +0,0 @@ -// Copyright 2000 Samuele Pedroni - -package org.python.core; - -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.util.Map; - -public abstract class AutoInternalTables extends InternalTables { - - protected transient ReferenceQueue queue = new ReferenceQueue(); - - protected abstract Reference newAutoRef(short type, Object key, - Object obj); - protected abstract short getAutoRefType(Reference ref); - protected abstract Object getAutoRefKey(Reference ref); - - private synchronized void cleanup() { - if (this.keepstable >= this.GSTABLE) - return; - this.adapters.remove(null); // trick - Reference ref; - while ((ref = this.queue.poll()) != null) { - Object key = getAutoRefKey(ref); - switch(getAutoRefType(ref)) { - case JCLASS: - Class cl = (Class)key; - this.classes.remove(cl); - classesDec(cl.getName()); - break; - case LAZY_JCLASS: - this.lazyClasses.remove(key); - break; - case ADAPTER_CLASS: - this.adapterClasses.remove(key); - } - } - } - - - protected boolean queryCanonical(String name) { - cleanup(); - return super.queryCanonical(name); - } - - protected PyJavaClass getCanonical(Class c) { - cleanup(); - Reference ref = (Reference)classesGet(c); - if (ref == null) return null; - return (PyJavaClass)ref.get(); - } - - protected PyJavaClass getLazyCanonical(String name) { - cleanup(); - Reference ref = (Reference)this.lazyClasses.get(name); - if (ref == null) return null; - return (PyJavaClass)ref.get(); - } - - protected void putCanonical(Class c,PyJavaClass canonical) { - cleanup(); - classesPut(c,newAutoRef(JCLASS,c,canonical)); - } - - protected void putLazyCanonical(String name,PyJavaClass canonical) { - cleanup(); - this.lazyClasses.put(name,newAutoRef(LAZY_JCLASS,name,canonical)); - } - - protected Class getAdapterClass(Class c) { - cleanup(); - Reference ref = (Reference)this.adapterClasses.get(c); - if (ref == null) return null; - return (Class)ref.get(); - } - - protected void putAdapterClass(Class c,Class ac) { - cleanup(); - this.adapterClasses.put(c,newAutoRef(ADAPTER_CLASS,c,ac)); - } - - protected Object getAdapter(Object o,String evc) { - cleanup(); - return super.getAdapter(o,evc); - } - - protected void putAdapter(Object o,String evc,Object ad) { - cleanup(); - super.putAdapter(o,evc,ad); - } - - - public boolean _doesSomeAutoUnload() { return true; } - - public void _forceCleanup() { cleanup(); } - - public void _beginCanonical() { - cleanup(); - super._beginCanonical(); - } - - public void _beginLazyCanonical() { - cleanup(); - super._beginLazyCanonical(); - } - - public void _beginOverAdapterClasses() { - cleanup(); - super._beginOverAdapterClasses(); - - } - - public void _beginOverAdapters() { - cleanup(); - super._beginOverAdapters(); - } - - public Object _next() { - if (this.iterType == ADAPTER) { - Object ret = super._next(); - if (ret != null) return ret; - } else { - while(this.iter.hasNext()) { - this.cur = this.iter.next(); - switch(this.iterType) { - case JCLASS: - PyJavaClass jc = (PyJavaClass)((Reference)this.cur).get(); - if (jc == null ) continue; - this.cur = jc; - return jc; - case LAZY_JCLASS: - PyJavaClass lazy = (PyJavaClass)((Reference)this.cur).get(); - if (lazy == null) continue; - return new _LazyRep(lazy.__name__,lazy.__mgr__); - case ADAPTER_CLASS: - Map.Entry entry = (Map.Entry)this.cur; - if (((Reference)entry.getValue()).get() == null ) - continue; - return entry.getKey(); - } - } - this.cur = null; - this.iter = null; - endStable(); - } - cleanup(); - return null; - } - - public void _flush(PyJavaClass jc) { - cleanup(); - super._flush(jc); - } - -} Deleted: branches/newstyle-java-types/src/org/python/core/CollectionProxy.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/CollectionProxy.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/CollectionProxy.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,295 +0,0 @@ -// Copyright (c) Corporation for National Research Initiatives - -package org.python.core; - -import java.util.Dictionary; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -class CollectionProxy { - public static final CollectionProxy NoProxy = new EnumerationProxy(null); - - public static CollectionProxy findCollection(Object object) { - if (object == null) - return NoProxy; - - if (object instanceof List) { - return new ListProxy(((List) object)); - } - if (object instanceof Map) { - return new MapProxy(((Map) object)); - } - if (object instanceof Iterable) { - return new IteratorProxy(((Iterable) object).iterator()); - } - if (object instanceof Iterator) { - return new IteratorProxy(((Iterator) object)); - } - - - if (object instanceof Vector) { - return new VectorProxy(((Vector) object)); - } - if (object instanceof Enumeration) { - return new EnumerationProxy(((Enumeration) object)); - } - if (object instanceof Dictionary) { - return new DictionaryProxy(((Dictionary) object)); - } - - return NoProxy; - } - - /** The basic functions to implement a mapping */ - public int __len__() { - throw Py.AttributeError("__len__"); - } - - public PyObject __finditem__(int key) { - return __finditem__(new PyInteger(key)); - } - - public PyObject __finditem__(PyObject key) { - throw Py.AttributeError("__getitem__"); - } - - public PyObject __getitem__(int key) { - PyObject ret = __finditem__(key); - if (ret == null) - throw Py.KeyError("" + key); - return ret; - } - - public PyObject __getitem__(PyObject key) { - PyObject ret = __finditem__(key); - if (ret == null) - throw Py.KeyError(key.toString()); - return ret; - } - - public void __setitem__(PyObject key, PyObject value) { - throw Py.AttributeError("__setitem__"); - } - - public void __delitem__(PyObject key) { - throw Py.AttributeError("__delitem__"); - } -} - -class EnumerationProxy extends CollectionProxy { - Enumeration proxy; - - int counter; - - public EnumerationProxy(Enumeration proxy) { - this.proxy = proxy; - this.counter = 0; - } - - public PyObject __finditem__(int key) { - if (key != this.counter) { - throw Py.ValueError("enumeration indices must be consecutive ints starting at 0"); - } - this.counter++; - if (this.proxy.hasMoreElements()) { - return Py.java2py(this.proxy.nextElement()); - } else { - return null; - } - } - - public PyObject __finditem__(PyObject key) { - if (key instanceof PyInteger) { - return __finditem__(((PyInteger) key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } -} - -class VectorProxy extends CollectionProxy { - Vector proxy; - - public VectorProxy(Vector proxy) { - this.proxy = proxy; - } - - public int __len__() { - return this.proxy.size(); - } - - public PyObject __finditem__(int key) { - try { - return Py.java2py(this.proxy.elementAt(key)); - } catch (ArrayIndexOutOfBoundsException exc) { - return null; - } - } - - public PyObject __finditem__(PyObject key) { - if (key instanceof PyInteger) { - return __finditem__(((PyInteger) key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } - - public void __setitem__(PyObject key, PyObject value) { - if (key instanceof PyInteger) { - this.proxy.setElementAt(Py.tojava(value, Object.class), ((PyInteger)key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } - - public void __delitem__(PyObject key) { - if (key instanceof PyInteger) { - this.proxy.removeElementAt(((PyInteger) key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } -} - -class DictionaryProxy extends CollectionProxy { - Dictionary proxy; - - public DictionaryProxy(Dictionary proxy) { - this.proxy = proxy; - } - - public int __len__() { - return this.proxy.size(); - } - - public PyObject __finditem__(int key) { - throw Py.TypeError("loop over non-sequence"); - } - - public PyObject __finditem__(PyObject key) { - return Py.java2py(this.proxy.get(Py.tojava(key, Object.class))); - } - - public void __setitem__(PyObject key, PyObject value) { - this.proxy.put(Py.tojava(key, Object.class), Py.tojava(value, - Object.class)); - } - - public void __delitem__(PyObject key) { - this.proxy.remove(Py.tojava(key, Object.class)); - } -} -class ListProxy extends CollectionProxy { - List proxy; - - public ListProxy(List proxy) { - this.proxy = proxy; - } - - public int __len__() { - return this.proxy.size(); - } - - public PyObject __finditem__(int key) { - try { - return Py.java2py(this.proxy.get(key)); - } catch (IndexOutOfBoundsException exc) { - return null; - } - } - - public PyObject __finditem__(PyObject key) { - if (key instanceof PyInteger) { - return __finditem__(((PyInteger) key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } - - public void __setitem__(int key, PyObject value) { - this.proxy.set(key, Py.tojava(value, Object.class)); - } - - public void __setitem__(PyObject key, PyObject value) { - if (key instanceof PyInteger) { - __setitem__(((PyInteger) key).getValue(), value); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } - - public void __delitem__(int key) { - this.proxy.remove(key); - } - - public void __delitem__(PyObject key) { - if (key instanceof PyInteger) { - __delitem__(((PyInteger) key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } -} - -class MapProxy extends CollectionProxy { - Map proxy; - - public MapProxy(Map proxy) { - this.proxy = proxy; - } - - public int __len__() { - return this.proxy.size(); - } - - public PyObject __finditem__(int key) { - throw Py.TypeError("loop over non-sequence"); - } - - public PyObject __finditem__(PyObject key) { - return Py.java2py(this.proxy.get(Py.tojava(key, Object.class))); - } - - public void __setitem__(PyObject key, PyObject value) { - this.proxy.put(Py.tojava(key, Object.class), Py.tojava(value, - Object.class)); - } - - public void __delitem__(PyObject key) { - this.proxy.remove(Py.tojava(key, Object.class)); - } -} - -class IteratorProxy extends CollectionProxy { - Iterator proxy; - - int counter; - - public IteratorProxy(Iterator proxy) { - this.proxy = proxy; - this.counter = 0; - } - - public PyObject __finditem__(int key) { - if (key != this.counter) { - throw Py.ValueError("iterator indices must be consecutive ints starting at 0"); - } - this.counter++; - if (this.proxy.hasNext()) { - return Py.java2py(this.proxy.next()); - } else { - return null; - } - } - - public PyObject __finditem__(PyObject key) { - if (key instanceof PyInteger) { - return __finditem__(((PyInteger) key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } -} Modified: branches/newstyle-java-types/src/org/python/core/IdImpl.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/IdImpl.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/IdImpl.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -7,48 +7,48 @@ public class IdImpl { public static class WeakIdentityMap { - + private transient ReferenceQueue refqueue = new ReferenceQueue(); private HashMap hashmap = new HashMap(); - + private void cleanup() { Object k; while ((k = this.refqueue.poll()) != null) { this.hashmap.remove(k); } } - + private class WeakIdKey extends WeakReference { private int hashcode; - + WeakIdKey(Object obj) { super(obj,WeakIdentityMap.this.refqueue); - this.hashcode = System.identityHashCode(obj); + this.hashcode = System.identityHashCode(obj); } - + public int hashCode() { return this.hashcode; } - + public boolean equals(Object other) { Object obj = this.get(); if (obj != null) { return obj == ((WeakIdKey)other).get(); } else { return this == other; - } + } } } - + public int _internal_map_size() { return this.hashmap.size(); } - + public void put(Object key,Object val) { cleanup(); this.hashmap.put(new WeakIdKey(key),val); } - + public Object get(Object key) { cleanup(); return this.hashmap.get(new WeakIdKey(key)); @@ -56,20 +56,20 @@ public void remove(Object key) { cleanup(); - this.hashmap.remove(new WeakIdKey(key)); + this.hashmap.remove(new WeakIdKey(key)); } } private WeakIdentityMap id_map = new WeakIdentityMap(); - private long sequential_id = 0; + private long sequential_id = 0; public long id(PyObject o) { - if (o instanceof PyJavaInstance) { - return java_obj_id(((PyJavaInstance)o).javaProxy); + if (o.getType() instanceof PyJavaType) { + return java_obj_id(o.javaProxy); } else { return java_obj_id(o); - } + } } // XXX maybe should display both this id and identityHashCode @@ -82,9 +82,9 @@ Long cand = (Long)this.id_map.get(o); if (cand == null) { this.sequential_id++; - long new_id = this.sequential_id; + long new_id = this.sequential_id; this.id_map.put(o,new Long(new_id)); - return new_id; + return new_id; } return cand.longValue(); } Deleted: branches/newstyle-java-types/src/org/python/core/InternalTables.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/InternalTables.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/InternalTables.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,292 +0,0 @@ -// Copyright 2000 Samuele Pedroni -package org.python.core; - -import java.lang.ref.WeakReference; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.StringTokenizer; -import java.util.WeakHashMap; - -import org.python.core.packagecache.PackageManager; - -public class InternalTables { - - // x__ --> org.python.core.X__InternalTables - // (x|X)__> --> org.python.core.X__InternalTables - // other (X__|__.__) --> other - // - private static InternalTables tryImpl(String id) { - try { - if(id.indexOf('.') < 0) { - if(id.charAt(id.length() - 1) == '>') { - id = makeCoreInternalTablesClass(id.substring(0, id.length() - 1)); - } else if(Character.isLowerCase(id.charAt(0))) { - id = makeCoreInternalTablesClass(id); - } - } - // System.err.println("*InternalTables*-create-try: "+id); - return (InternalTables)Class.forName(id).newInstance(); - } catch(Throwable e) { - // System.err.println(" exc: "+e); // ??dbg - return null; - } - } - - private static String makeCoreInternalTablesClass(String id) { - if(Character.isLowerCase(id.charAt(0))) { - id = Character.toUpperCase(id.charAt(0)) + id.substring(1); - } - return "org.python.core." + id + "InternalTables"; - } - - static InternalTables createInternalTables() { - if(PySystemState.registry == null) { - throw new IllegalStateException("Jython interpreter state not initialized. " - + "You need to call PySystemState.initialize or PythonInterpreter.initialize."); - } - String cands = PySystemState.registry.getProperty("python.options.internalTablesImpl"); - if(cands == null) { - return new InternalTables(); - } - StringTokenizer candEnum = new StringTokenizer(cands, ":"); - while(candEnum.hasMoreTokens()) { - InternalTables tbl = tryImpl(candEnum.nextToken().trim()); - if(tbl != null) { - return tbl; - } - } - return new InternalTables(); - } - - final protected static short JCLASS = 0; - - final protected static short LAZY_JCLASS = 1; - - final protected static short ADAPTER_CLASS = 2; - - final protected static short ADAPTER = 3; - - protected Map classes = new HashMap(); - - protected Map temp = new HashMap();; - - protected Map counters = new HashMap();; - - protected Map lazyClasses = new HashMap();; - - protected Map adapterClasses = new HashMap();; - - protected final short GSTABLE = 1; - - protected final short JCSTABLE = 2; - - protected short keepstable; - - protected void commitTemp() { - this.classes.putAll(this.temp); - this.temp.clear(); - } - - protected WeakHashMap adapters = new WeakHashMap();; - - protected Object getAdapter(Object o, String evc) { - HashMap ads = (HashMap)this.adapters.get(o); - if(ads == null) { - return null; - } - WeakReference adw = (WeakReference)ads.get(evc); - if(adw == null) { - return null; - } - return adw.get(); - } - - protected void putAdapter(Object o, String evc, Object ad) { - HashMap ads = (HashMap)this.adapters.get(o); - if(ads == null) { - ads = new HashMap(); - this.adapters.put(o, ads); - } - ads.put(evc, new WeakReference(ad)); - } - - protected Iterator iter; - - protected Iterator grand; - - protected short iterType; - - protected Object cur; - - protected void beginStable(short lvl) { - this.keepstable = lvl; - } - - protected void endStable() { - if(this.keepstable == this.JCSTABLE) - commitTemp(); - this.keepstable = 0; - } - - protected void classesPut(Class c, Object jc) { - if(this.keepstable == this.JCSTABLE) { - this.temp.put(c, jc); - // System.err.println("temp-defer-canonical: "+c.getName()); - } else { - this.classes.put(c, jc); - } - String name = c.getName(); - Integer cnt = (Integer)this.counters.get(name); - if(cnt == null) { - this.counters.put(name, new Integer(1)); - this.lazyClasses.remove(name); - } else { - this.counters.put(name, new Integer(cnt.intValue() + 1)); - } - } - - protected Object classesGet(Class c) { - Object o = this.classes.get(c); - if(o != null || this.keepstable != this.JCSTABLE) - return o; - return this.temp.get(c); - } - - public void _beginCanonical() { - beginStable(this.JCSTABLE); - this.iter = this.classes.values().iterator(); - this.iterType = JCLASS; - } - - public void _beginLazyCanonical() { - beginStable(this.GSTABLE); - this.iter = this.lazyClasses.values().iterator(); - this.iterType = LAZY_JCLASS; - } - - public void _beginOverAdapterClasses() { - beginStable(this.GSTABLE); - this.iter = this.adapterClasses.entrySet().iterator(); - this.iterType = ADAPTER_CLASS; - } - - public void _beginOverAdapters() { - beginStable((short)0); - this.grand = this.adapters.values().iterator(); - this.iter = null; - this.iterType = ADAPTER; - } - - public Object _next() { - if(this.iterType == ADAPTER) { - for(;;) { - if(this.iter == null || !this.iter.hasNext()) { - if(this.grand.hasNext()) { - this.cur = this.grand.next(); - this.iter = ((HashMap)this.cur).values().iterator(); - } else { - this.iter = null; - } - } - if(this.iter != null) { - WeakReference adw = (WeakReference)this.iter.next(); - Object ad = adw.get(); - if(ad != null) { - return ad.getClass().getInterfaces()[0]; - } else { - continue; - } - } - this.grand = null; - break; - } - } else if(this.iter.hasNext()) { - this.cur = this.iter.next(); - switch(this.iterType){ - case JCLASS: - return this.cur; - case LAZY_JCLASS: - PyJavaClass lazy = (PyJavaClass)this.cur; - return new _LazyRep(lazy.__name__, lazy.__mgr__); - case ADAPTER_CLASS: - Map.Entry entry = (Map.Entry)this.cur; - return entry.getKey(); - } - } - this.cur = null; - endStable(); - this.iter = null; - return null; - } - - public void _flushCurrent() { - this.iter.remove(); - switch(this.iterType){ - case JCLASS: - classesDec(((PyJavaClass)this.cur).__name__); - break; - case ADAPTER: - if(((HashMap)this.cur).size() == 0) - this.grand.remove(); - } - } - - public void _flush(PyJavaClass jc) { - Class c = jc.proxyClass; - if(c == null) { - this.lazyClasses.remove(jc.__name__); - } else { - this.classes.remove(c); - classesDec(jc.__name__); - } - } - - protected Class getAdapterClass(Class c) { - return (Class)this.adapterClasses.get(c); - } - - protected PyJavaClass getCanonical(Class c) { - return (PyJavaClass)classesGet(c); - } - - protected PyJavaClass getLazyCanonical(String name) { - return (PyJavaClass)this.lazyClasses.get(name); - } - - protected void putAdapterClass(Class c, Class ac) { - this.adapterClasses.put(c, ac); - } - - protected void putCanonical(Class c, PyJavaClass canonical) { - classesPut(c, canonical); - } - - protected void putLazyCanonical(String name, PyJavaClass canonical) { - this.lazyClasses.put(name, canonical); - } - - protected boolean queryCanonical(String name) { - return this.counters.get(name) != null || this.lazyClasses.get(name) != null; - } - - protected void classesDec(String name) { - int c = ((Integer)this.counters.get(name)).intValue(); - if(c == 1) - this.counters.remove(name); - else - this.counters.put(name, new Integer(c - 1)); - } - - static public class _LazyRep { - - public String name; - - public PackageManager mgr; - - _LazyRep(String name, PackageManager mgr) { - this.name = name; - this.mgr = mgr; - } - } -} Modified: branches/newstyle-java-types/src/org/python/core/Py.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/Py.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/Py.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -435,8 +435,8 @@ } else if (t instanceof OutOfMemoryError) { memory_error((OutOfMemoryError) t); } - PyJavaInstance exc = new PyJavaInstance(t); - PyException pyex = new PyException(exc.instclass, exc); + PyObject exc = PyJavaType.wrapJavaObject(t); + PyException pyex = new PyException(exc.getType(), exc); // Set the cause to the original throwable to preserve // the exception chain. pyex.initCause(t); @@ -722,7 +722,7 @@ // Pre-initialize the PyJavaClass for OutOfMemoryError so when we need // it it creating the pieces for it won't cause an additional out of // memory error. Fix for bug #1654484 - PyJavaClass.lookup(OutOfMemoryError.class); + PyType.fromClass(OutOfMemoryError.class); } public static PySystemState defaultSystemState; // This is a hack to get initializations to work in proper order @@ -981,7 +981,7 @@ } } - if (value instanceof PyJavaInstance) { + if (value.getType() instanceof PyJavaType) { Object javaError = value.__tojava__(Throwable.class); if (javaError != null && javaError != Py.NoConversion) { @@ -1134,14 +1134,14 @@ // java.io.IOExceptions. This is a hack for 1.0.x until I can do // it right in 1.1 if (exc == Py.IOError) { - if (__builtin__.isinstance(pye.value, PyJavaClass.lookup(IOException.class))) { + if (__builtin__.isinstance(pye.value, PyType.fromClass(IOException.class))) { return true; } } // FIXME too, same approach for OutOfMemoryError if (exc == Py.MemoryError) { if (__builtin__.isinstance(pye.value, - PyJavaClass.lookup(OutOfMemoryError.class))) { + PyType.fromClass(OutOfMemoryError.class))) { return true; } } @@ -1518,7 +1518,7 @@ if (doc != null && dict.__finditem__("__doc__") == null) { dict.__setitem__("__doc__", doc); } - return makeClass(name, bases, dict, null); + return makeClass(name, bases, dict); } public static PyObject makeClass(String name, PyObject base, PyObject dict) { @@ -1526,10 +1526,6 @@ return makeClass(name, bases, dict); } - public static PyObject makeClass(String name, PyObject[] bases, PyObject dict) { - return makeClass(name, bases, dict, null); - } - /** * Create a new Python class. * @@ -1537,11 +1533,9 @@ * @param bases an array of PyObject base classes * @param dict the class's namespace, containing the class body * definition - * @param proxyClass an optional underlying Java class * @return a new Python Class PyObject */ - public static PyObject makeClass(String name, PyObject[] bases, PyObject dict, - Class proxyClass) { + public static PyObject makeClass(String name, PyObject[] bases, PyObject dict) { PyFrame frame = getFrame(); if (dict.__finditem__("__module__") == null) { @@ -1568,9 +1562,7 @@ } } - if (metaclass == null || metaclass == CLASS_TYPE || - (metaclass instanceof PyJavaClass && - ((PyJavaClass)metaclass).proxyClass == Class.class)) { + if (metaclass == null || metaclass == CLASS_TYPE) { boolean moreGeneral = false; for (PyObject base : bases) { if (!(base instanceof PyClass)) { @@ -1580,14 +1572,10 @@ } } if (!moreGeneral) { - return new PyClass(name, new PyTuple(bases), dict, proxyClass); + return new PyClass(name, new PyTuple(bases), dict); } } - if (proxyClass != null) { - throw Py.TypeError("the meta-class cannot handle java subclassing"); - } - try { return metaclass.__call__(new PyString(name), new PyTuple(bases), dict); } catch (PyException pye) { @@ -1946,7 +1934,7 @@ name = "fixed file"; this.file = file; - if (file instanceof PyJavaInstance) { + if (file.getType() instanceof PyJavaType) { Object tojava = file.__tojava__(OutputStream.class); if (tojava != null && tojava != Py.NoConversion) { this.file = new PyFile((OutputStream) tojava); Modified: branches/newstyle-java-types/src/org/python/core/PyBeanEventProperty.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyBeanEventProperty.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/PyBeanEventProperty.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,9 +1,14 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; +import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.util.Map; +import java.util.WeakHashMap; +import org.python.util.Generic; + public class PyBeanEventProperty extends PyReflectedField { public Method addMethod; @@ -51,22 +56,40 @@ } private synchronized static Class<?> getAdapterClass(Class<?> c) { - InternalTables tbl = PyJavaClass.getInternalTables(); - Class<?> o = tbl.getAdapterClass(c); - if (o != null) - return o; Class<?> pc = Py.findClass("org.python.proxies." + c.getName() + "$Adapter"); if (pc == null) { pc = MakeProxies.makeAdapter(c); } - tbl.putAdapterClass(c, pc); return pc; } + protected Map<Object, Map<String, WeakReference<Object>>> adapters = + new WeakHashMap<Object, Map<String, WeakReference<Object>>>(); + + protected Object getAdapter(Object o, String evc) { + Map<String, WeakReference<Object>> ads = adapters.get(o); + if (ads == null) { + return null; + } + WeakReference<Object> adw = ads.get(evc); + if (adw == null) { + return null; + } + return adw.get(); + } + + protected void putAdapter(Object o, String evc, Object ad) { + Map<String, WeakReference<Object>> ads = adapters.get(o); + if(ads == null) { + ads = Generic.map(); + adapters.put(o, ads); + } + ads.put(evc, new WeakReference<Object>(ad)); + } + private synchronized Object getAdapter(Object self) { - InternalTables tbl = PyJavaClass.getInternalTables(); String eventClassName = eventClass.getName(); - Object adapter = tbl.getAdapter(self, eventClassName); + Object adapter = getAdapter(self, eventClassName); if (adapter != null) return adapter; try { @@ -75,7 +98,7 @@ } catch (Exception e) { throw Py.JavaError(e); } - tbl.putAdapter(self, eventClassName, adapter); + putAdapter(self, eventClassName, adapter); return adapter; } Modified: branches/newstyle-java-types/src/org/python/core/PyClass.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyClass.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/PyClass.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,15 +1,9 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.io.Serializable; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - /** * A python class. */ - public class PyClass extends PyObject { /** * Holds the namespace for this class @@ -31,13 +25,6 @@ PyObject __getattr__, __setattr__, __delattr__, __tojava__, __del__, __contains__; - // Holds the classes for which this is a proxy - // Only used when subclassing from a Java class - protected Class<?> proxyClass; - - // xxx map 'super__*' names -> array of methods - protected java.util.HashMap super__methods; - protected PyClass() { super(); } @@ -53,120 +40,12 @@ * @see org.python.core.Py#makeClass(String, PyObject[], PyCode, PyObject) */ public PyClass(String name, PyTuple bases, PyObject dict) { - this(name, bases, dict, null); - } - - /** - * Create a python class which inherits from a java class and where we - * already have generated a proxyclass. If we do not have a pre-generated - * proxyclass, the class initialization method will create such a proxyclass - * if bases contain a java class. - * - * @param name name of the class. - * @param bases A list of base classes. - * @param dict The class dict. Normally this dict is returned by the class - * code object. - * - * @see org.python.core.Py#makeClass(String, PyObject[], PyCode, PyObject, - * Class) - */ - public PyClass(String name, PyTuple bases, PyObject dict, Class proxyClass) { - this.proxyClass = proxyClass; - init(name, bases, dict); - } - - protected Class<?> getProxyClass() { - return proxyClass; - } - - void init(String name, PyTuple bases, PyObject dict) { __name__ = name; __bases__ = bases; __dict__ = dict; findModule(dict); - if (proxyClass == null) { - List<Class<?>> interfaces = new ArrayList<Class<?>>(); - Class<?> baseClass = null; - for (int i = 0; i < bases.size(); i++) { - Object base = bases.pyget(i); - if (base instanceof PyType) { - // xxx this works in CPython, which checks for a callable here - throw Py.TypeError("can't transmogrify old-style class into new-style " - + "class inheriting from " + ((PyType)base).getName()); - } else if (!(base instanceof PyClass)) { - throw Py.TypeError("base must be a class"); - } - Class<?> proxy = ((PyClass) base).getProxyClass(); - if (proxy != null) { - if (proxy.isInterface()) { - interfaces.add(proxy); - } else { - if (baseClass != null) { - throw Py.TypeError("no multiple inheritance for Java classes: " - + proxy.getName() + " and " + baseClass.getName()); - } - baseClass = proxy; - } - } - } - if (baseClass != null || interfaces.size() != 0) { - String proxyName = __name__; - PyObject module = dict.__finditem__("__module__"); - if (module != null) { - proxyName = module.toString() + "$" + __name__; - } - proxyClass = MakeProxies.makeProxy(baseClass, interfaces, - __name__, proxyName, __dict__); - } - } - - if (proxyClass != null) { - // xxx more efficient way without going through a PyJavaClass? - PyObject superDict = PyJavaClass.lookup(proxyClass).__findattr__( - "__dict__"); // xxx getDict perhaps? - // This code will add in the needed super__ methods to the class - PyObject snames = superDict.__finditem__("__supernames__"); - if (snames != null) { - for (PyObject item : snames.asIterable()) { - if (__dict__.__finditem__(item) == null) { - PyObject superFunc = superDict.__finditem__(item); - if (superFunc != null) { - __dict__.__setitem__(item, superFunc); - } - } - } - } - - // xxx populate super__methods, experiment. - - java.lang.reflect.Method proxy_methods[] = proxyClass.getMethods(); - - super__methods = new java.util.HashMap(); - - for (Method meth : proxy_methods) { - String meth_name = meth.getName(); - if (meth_name.startsWith("super__")) { - java.util.ArrayList samename = (java.util.ArrayList) super__methods - .get(meth_name); - if (samename == null) { - samename = new java.util.ArrayList(); - super__methods.put(meth_name, samename); - } - samename.add(meth); - } - } - - java.lang.reflect.Method[] empty_methods = new java.lang.reflect.Method[0]; - for (java.util.Iterator iter = super__methods.entrySet().iterator(); iter - .hasNext();) { - java.util.Map.Entry entry = (java.util.Map.Entry) iter.next(); - entry.setValue(((java.util.ArrayList) entry.getValue()) - .toArray(empty_methods)); - } - } - if (dict.__finditem__("__doc__") == null) { dict.__setitem__("__doc__", Py.None); } @@ -193,14 +72,6 @@ } } - public Object __tojava__(Class<?> c) { - if ((c == Object.class || c == Class.class || c == Serializable.class) - && proxyClass != null) { - return proxyClass; - } - return super.__tojava__(c); - } - // returns [PyObject, PyClass] PyObject[] lookupGivingClass(String name, boolean stop_at_java) { PyObject result = __dict__.__finditem__(name); @@ -348,11 +219,6 @@ if (this == superclass) { return true; } - if (getProxyClass() != null && superclass.getProxyClass() != null) { - if (superclass.proxyClass.isAssignableFrom(this.proxyClass)) { - return true; - } - } if (this.__bases__ == null || superclass.__bases__ == null) { return false; } Modified: branches/newstyle-java-types/src/org/python/core/PyFile.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyFile.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/PyFile.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -473,7 +473,7 @@ @ExposedMethod final PyObject file_fileno() { - return new PyJavaInstance(file.fileno()); + return PyJavaType.wrapJavaObject(file.fileno()); } @ExposedMethod(names = {"__str__", "__repr__"}) Modified: branches/newstyle-java-types/src/org/python/core/PyInstance.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyInstance.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/PyInstance.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,8 +1,6 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; import java.util.Hashtable; -import java.util.StringTokenizer; -import java.io.Serializable; /** * A python class instance. @@ -38,8 +36,6 @@ PyClass pyc = (PyClass)mod.__getattr__(name.intern()); instclass = pyc; - if (javaProxy != null) - ((PyProxy) javaProxy)._setPySystemState(Py.getSystemState()); } private void writeObject(java.io.ObjectOutputStream out) @@ -82,47 +78,7 @@ private static Hashtable primitiveMap; - protected void makeProxy() { - Class c = instclass.proxyClass; - PyProxy proxy; - ThreadState ts = Py.getThreadState(); - try { - ts.pushInitializingProxy(this); - try { - proxy = (PyProxy)c.newInstance(); - } catch (java.lang.InstantiationException e) { - Class sup = c.getSuperclass(); - String msg = "Default constructor failed for Java superclass"; - if (sup != null) - msg += " " + sup.getName(); - throw Py.TypeError(msg); - } catch (NoSuchMethodError nsme) { - throw Py.TypeError("constructor requires arguments"); - } catch (Exception exc) { - throw Py.JavaError(exc); - } - } finally { - ts.popInitializingProxy(); - } - - if (javaProxy != null && javaProxy != proxy) { - // The javaProxy can be initialized in Py.jfindattr() - throw Py.TypeError("Proxy instance already initialized"); - } - PyObject proxyInstance = proxy._getPyInstance(); - if (proxyInstance != null && proxyInstance != this) { - // The proxy was initialized to another instance!! - throw Py.TypeError("Proxy initialization conflict"); - } - - javaProxy = proxy; - } - public Object __tojava__(Class c) { - if ((c == Object.class || c == Serializable.class) && - javaProxy != null) { - return javaProxy; - } if (c.isInstance(this)) return this; @@ -143,15 +99,9 @@ c = tmp; } - if (javaProxy == null && instclass.proxyClass != null) { - makeProxy(); - } - if (c.isInstance(javaProxy)) - return javaProxy; - if (instclass.__tojava__ != null) { // try { - PyObject ret = instclass.__tojava__.__call__(this, PyJavaClass.lookup(c)); + PyObject ret = instclass.__tojava__.__call__(this, PyType.fromClass(c)); if (ret == Py.None) return Py.NoConversion; @@ -185,10 +135,6 @@ else if (ret != Py.None) { throw Py.TypeError("__init__() should return None"); } - // Now init all superclasses that haven't already been initialized - if (javaProxy == null && instclass.proxyClass != null) { - makeProxy(); - } } public PyObject __jfindattr__(String name) { @@ -325,16 +271,7 @@ if (setter != null) { setter.__call__(this, new PyString(name), value); } else { - if (instclass.getProxyClass() != null) { - PyObject field = instclass.lookup(name, false); - if (field == null) { - noField(name, value); - } else if (!field.jtryset(this, value)) { - unassignableField(name, value); - } - } else { - __dict__.__setitem__(name, value); - } + __dict__.__setitem__(name, value); } } @@ -548,11 +485,6 @@ } catch (PyException exc) { } if (meth == null) { - // Copied form __len__() - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - return proxy.__len__() != 0 ? true : false; - } try { meth = __findattr__("__len__"); } catch (PyException exc) { } @@ -564,20 +496,7 @@ return ret.__nonzero__(); } - private CollectionProxy collectionProxy=null; - - private CollectionProxy getCollection() { - if (collectionProxy == null) - collectionProxy = CollectionProxy.findCollection(javaProxy); - return collectionProxy; - } - public int __len__() { - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - return proxy.__len__(); - } - PyObject ret = invoke("__len__"); if (ret instanceof PyInteger) return ((PyInteger)ret).getValue(); @@ -585,10 +504,6 @@ } public PyObject __finditem__(int key) { - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - return proxy.__finditem__(key); - } return __finditem__(new PyInteger(key)); } @@ -614,11 +529,6 @@ } public PyObject __finditem__(PyObject key) { - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - return proxy.__finditem__(key); - } - try { return invoke("__getitem__", key); } catch (PyException e) { @@ -631,32 +541,14 @@ } public PyObject __getitem__(PyObject key) { - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - PyObject ret = proxy.__finditem__(key); - if (ret == null) { - throw Py.KeyError(key.toString()); - } - return ret; - } return invoke("__getitem__", key); } public void __setitem__(PyObject key, PyObject value) { - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - proxy.__setitem__(key, value); - return; - } invoke("__setitem__", key, value); } public void __delitem__(PyObject key) { - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - proxy.__delitem__(key); - return; - } invoke("__delitem__", key); } @@ -688,10 +580,6 @@ } public PyObject __iter__() { - PyObject iter = getCollectionIter(); - if (iter != null) { - return iter; - } PyObject func = __findattr__("__iter__"); if (func != null) return func.__call__(); @@ -715,37 +603,6 @@ throw Py.TypeError("instance has no next() method"); } - private static CollectionIter[] iterFactories; - - private PyObject getCollectionIter() { - if (iterFactories == null) - initializeIterators(); - for (int i = 0; iterFactories[i] != null; i++) { - PyObject iter = iterFactories[i].findCollection(javaProxy); - if (iter != null) - return iter; - } - return null; - } - - private static synchronized void initializeIterators() { - if (iterFactories != null) - return; - String factories = PySystemState.registry.getProperty("python.collections", ""); - int i = 0; - StringTokenizer st = new StringTokenizer(factories, ","); - iterFactories = new CollectionIter[st.countTokens() + 2]; - iterFactories[0] = new CollectionIter(); - while (st.hasMoreTokens()) { - String s = st.nextToken(); - try { - Class factoryClass = Class.forName(s); - CollectionIter factory = (CollectionIter)factoryClass.newInstance(); - iterFactories[i++] = factory; - } catch (Throwable t) { } - } - } - public boolean __contains__(PyObject o) { PyObject func = __findattr__("__contains__"); if (func == null) Deleted: branches/newstyle-java-types/src/org/python/core/PyJavaClass.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaClass.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/PyJavaClass.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,774 +0,0 @@ -// Copyright (c) Corporation for National Research Initiatives -package org.python.core; - -import java.beans.Introspector; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.EventListener; - -import org.python.core.packagecache.PackageManager; - -/** - * A wrapper around a java class. - */ -public class PyJavaClass extends PyClass { - - private static InternalTables tbl; - - public PyReflectedConstructor __init__; - - public PackageManager __mgr__; - - public String __module__; - - private boolean initialized = false; - - // Prevent recursive calls to initialize() - private boolean initializing = false; - - public synchronized final static InternalTables getInternalTables() { - if (tbl == null) { - tbl = InternalTables.createInternalTables(); - } - return tbl; - } - - public final boolean isLazy() { - return proxyClass == null; - } - - public static final PyJavaClass lookup(String name, PackageManager mgr) { - if (tbl.queryCanonical(name)) { - Class<?> c = mgr.findClass(null, name, "forced java class"); - check_lazy_allowed(c); // xxx - return lookup(c); - } - PyJavaClass ret = new PyJavaClass(name, mgr); - tbl.putLazyCanonical(name, ret); - return ret; - } - - public synchronized static final PyJavaClass lookup(Class<?> c) { - if (tbl == null) { - tbl = new InternalTables(); - PyJavaClass jc = new PyJavaClass(); - jc.init(PyJavaClass.class); - tbl.putCanonical(PyJavaClass.class, jc); - } - PyJavaClass ret = tbl.getCanonical(c); - if (ret != null) - return ret; - PyJavaClass lazy = tbl.getLazyCanonical(c.getName()); - if (lazy != null) { - initLazy(lazy); - if (lazy.proxyClass == c) { - return lazy; - } - } - Class<?> parent = c.getDeclaringClass(); - ret = parent == null ? new PyJavaClass(c) : new PyJavaInnerClass(c, lookup(parent)); - tbl.putCanonical(c, ret); - return ret; - } - - private PyJavaClass() {} - - protected PyJavaClass(Class<?> c) { - init(c); - } - - /** - * Set the full name of this class. - */ - private void setName(String name) { - int dotIndex = name.lastIndexOf("."); - if (dotIndex == -1) { - __name__ = name; - __module__ = ""; - } else { - __name__ = name.substring(name.lastIndexOf(".") + 1, name.length()); - __module__ = name.substring(0, name.lastIndexOf(".")); - } - } - - private String fullName() { - if (__module__ == "") - return __name__; - else - return __module__ + "." + __name__; - } - - protected PyJavaClass(String name, PackageManager mgr) { - setName(name); - this.__mgr__ = mgr; - } - - protected void findModule(PyObject dict) {} - - protected Class<?> getProxyClass() { - initialize(); - return proxyClass; - } - - // for the moment trying to lazily load a PyObject subclass - // is not allowed, (because of the PyJavaClass vs PyType class mismatch) - // pending PyJavaClass becoming likely a subclass of PyType - private static final void check_lazy_allowed(Class<?> c) { - if (PyObject.class.isAssignableFrom(c)) { // xxx - throw Py.TypeError("cannot lazy load PyObject subclass"); - } - } - - private static final void initLazy(PyJavaClass jc) { - Class<?> c = jc.__mgr__.findClass(null, jc.fullName(), "lazy java class"); - check_lazy_allowed(c); // xxx - jc.init(c); - tbl.putCanonical(jc.proxyClass, jc); - jc.__mgr__ = null; - } - - private synchronized void initialize() { - if (initialized || initializing) { - return; - } - initializing = true; - synchronized (PyJavaClass.class) { - if (proxyClass == null) { - initLazy(this); - } - } - init__bases__(proxyClass); - ... [truncated message content] |
From: <pj...@us...> - 2008-11-23 01:57:14
|
Revision: 5606 http://jython.svn.sourceforge.net/jython/?rev=5606&view=rev Author: pjenvey Date: 2008-11-23 01:57:09 +0000 (Sun, 23 Nov 2008) Log Message: ----------- o allow open({In,Out}putStream) but with a deprecation warning. make open a function o add optional bufsize args to FileUtil.wrap fixes #1171 Modified Paths: -------------- trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/core/util/FileUtil.java Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2008-11-23 00:46:06 UTC (rev 5605) +++ trunk/jython/src/org/python/core/PyFile.java 2008-11-23 01:57:09 UTC (rev 5606) @@ -96,13 +96,19 @@ } /** - * Creates a file object wrapping the given <code>InputStream</code>. The builtin methods - * <code>file</code> and <code>open</code> don't expose this functionality as it isn't available - * to regular Python code. To wrap an InputStream in a file from Python, use + * Creates a file object wrapping the given <code>InputStream</code>. The builtin + * method <code>file</code> doesn't expose this functionality (<code>open</code> does + * albeit deprecated) as it isn't available to regular Python code. To wrap an + * InputStream in a file from Python, use + * {@link FileUtil#wrap(InputStream, int)} * {@link FileUtil#wrap(InputStream)} */ + public PyFile(InputStream istream, int bufsize) { + this(istream, "<Java InputStream '" + istream + "' as file>", "r", bufsize, true); + } + public PyFile(InputStream istream) { - this(istream, "<Java InputStream '" + istream + "' as file>", "r", -1, true); + this(istream, -1); } PyFile(OutputStream ostream, String name, String mode, int bufsize, boolean closefd) { @@ -111,13 +117,19 @@ } /** - * Creates a file object wrapping the given <code>OutputStream</code>. The builtin methods - * <code>file</code> and <code>open</code> don't expose this functionality as it isn't available - * to regular Python code. To wrap an OutputStream in a file from Python, use + * Creates a file object wrapping the given <code>OutputStream</code>. The builtin + * method <code>file</code> doesn't expose this functionality (<code>open</code> does + * albeit deprecated) as it isn't available to regular Python code. To wrap an + * OutputStream in a file from Python, use + * {@link FileUtil#wrap(OutputStream, int)} * {@link FileUtil#wrap(OutputStream)} */ + public PyFile(OutputStream ostream, int bufsize) { + this(ostream, "<Java OutputStream '" + ostream + "' as file>", "w", bufsize, true); + } + public PyFile(OutputStream ostream) { - this(ostream, "<Java OutputStream '" + ostream + "' as file>", "w", -1, true); + this(ostream, -1); } public PyFile(String name, String mode, int bufsize) { Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-11-23 00:46:06 UTC (rev 5605) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-11-23 01:57:09 UTC (rev 5606) @@ -1,6 +1,8 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; +import java.io.InputStream; +import java.io.OutputStream; import java.util.Iterator; import java.util.Map; @@ -305,7 +307,6 @@ dict.__setitem__("unicode", PyUnicode.TYPE); dict.__setitem__("basestring", PyBaseString.TYPE); dict.__setitem__("file", PyFile.TYPE); - dict.__setitem__("open", PyFile.TYPE); dict.__setitem__("slice", PySlice.TYPE); dict.__setitem__("xrange", PyXRange.TYPE); @@ -364,6 +365,7 @@ dict.__setitem__("vars", new BuiltinFunctions("vars", 41, 0, 1)); dict.__setitem__("zip", new BuiltinFunctions("zip", 43, 0, -1)); dict.__setitem__("compile", new CompileFunction()); + dict.__setitem__("open", new OpenFunction()); dict.__setitem__("reversed", new BuiltinFunctions("reversed", 45, 1)); dict.__setitem__("__import__", new ImportFunction()); dict.__setitem__("sorted", new SortedFunction()); @@ -1567,3 +1569,31 @@ return (modType)node; } } + +class OpenFunction extends PyBuiltinFunction { + OpenFunction() { + super("open", "Open a file using the file() type, returns a file object. This is the\n" + + "preferred way to open a file."); + } + + private static final String warning = + "Passing an Input/OutputStream to open is deprecated, use " + + "org.python.core.util.FileUtil.wrap(stream[, bufsize]) instead."; + + public PyObject __call__(PyObject args[], String kwds[]) { + ArgParser ap = new ArgParser("file", args, kwds, new String[] {"name", "mode", "bufsize"}, + 1); + PyObject obj = ap.getPyObject(0); + if (obj instanceof PyJavaInstance) { + int bufsize = ap.getInt(2, -1); + if (obj.javaProxy instanceof InputStream) { + Py.warning(Py.DeprecationWarning, warning); + return new PyFile((InputStream)obj.javaProxy, bufsize); + } else if (obj.javaProxy instanceof OutputStream) { + Py.warning(Py.DeprecationWarning, warning); + return new PyFile((OutputStream)obj.javaProxy, bufsize); + } + } + return PyFile.TYPE.__call__(args, kwds); + } +} Modified: trunk/jython/src/org/python/core/util/FileUtil.java =================================================================== --- trunk/jython/src/org/python/core/util/FileUtil.java 2008-11-23 00:46:06 UTC (rev 5605) +++ trunk/jython/src/org/python/core/util/FileUtil.java 2008-11-23 01:57:09 UTC (rev 5606) @@ -14,17 +14,31 @@ public class FileUtil { /** + * Creates a PyFile that reads from the given <code>InputStream</code> with bufsize. + */ + public static PyFile wrap(InputStream is, int bufsize) { + return new PyFile(is, bufsize); + } + + /** * Creates a PyFile that reads from the given <code>InputStream</code>. */ public static PyFile wrap(InputStream is) { - return new PyFile(is); + return wrap(is, -1); } /** + * Creates a PyFile that writes to the given <code>OutputStream</code> with bufsize. + */ + public static PyFile wrap(OutputStream os, int bufsize) { + return new PyFile(os, bufsize); + } + + /** * Creates a PyFile that writes to the given <code>OutputStream</code>. */ public static PyFile wrap(OutputStream os) { - return new PyFile(os); + return wrap(os, -1); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-23 00:46:12
|
Revision: 5605 http://jython.svn.sourceforge.net/jython/?rev=5605&view=rev Author: cgroves Date: 2008-11-23 00:46:06 +0000 (Sun, 23 Nov 2008) Log Message: ----------- Use PyJavaType to initialize array, not PyJavaClass Modified Paths: -------------- branches/newstyle-java-types/Lib/test/test_array_jy.py branches/newstyle-java-types/src/org/python/core/PyArray.java Modified: branches/newstyle-java-types/Lib/test/test_array_jy.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_array_jy.py 2008-11-23 00:18:15 UTC (rev 5604) +++ branches/newstyle-java-types/Lib/test/test_array_jy.py 2008-11-23 00:46:06 UTC (rev 5605) @@ -12,7 +12,7 @@ def test_jarray(self): # until it is fully formally removed - # While jarray is still being phased out, just flex the initilaizers. + # While jarray is still being phased out, just flex the initializers. # The rest of the test for array will catch all the big problems. import jarray jarray.array(range(5), 'i') @@ -23,7 +23,7 @@ def test_java_object_arrays(self): jStringArr = array(String, [String("a"), String("b"), String("c")]) self.assert_( - Arrays.equals(jStringArr.typecode, str(String)), + Arrays.equals(jStringArr.typecode, 'java.lang.String'), "String array typecode of wrong type, expected %s, found %s" % (jStringArr.typecode, str(String))) self.assertEqual(zeros(String, 5), Array.newInstance(String, 5)) Modified: branches/newstyle-java-types/src/org/python/core/PyArray.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyArray.java 2008-11-23 00:18:15 UTC (rev 5604) +++ branches/newstyle-java-types/src/org/python/core/PyArray.java 2008-11-23 00:46:06 UTC (rev 5605) @@ -21,7 +21,7 @@ /** * A wrapper class around native java arrays. - * + * * Instances of PyArray are created either by java functions or directly by the * jarray module. * <p> @@ -95,8 +95,8 @@ } typecode = obj.toString(); type = char2class(typecode.charAt(0)); - } else if (obj instanceof PyJavaClass) { - type = ((PyJavaClass)obj).proxyClass; + } else if (obj instanceof PyJavaType) { + type = ((PyJavaType)obj).underlying_class; typecode = type.getName(); } else { throw Py.TypeError("array() argument 1 must be char, not " + obj.getType().fastGetName()); @@ -153,7 +153,7 @@ /** * Create a PyArray storing <em>ctype</em> types and being initialised * with <em>initialiser</em>. - * + * * @param init * an initialiser for the array - can be PyString or PySequence * (including PyArray) or iterable type. @@ -325,7 +325,7 @@ /** * Adds (appends) two PyArrays together - * + * * @param other * a PyArray to be added to the instance * @return the result of the addition as a new PyArray instance @@ -348,7 +348,7 @@ /** * Length of the array - * + * * @return number of elements in the array */ public int __len__() { @@ -393,9 +393,9 @@ if (typecode.length() > 1) return typecode; else return "'" + typecode + "'"; } - + /** - * + * * @param c * target <em>Class</em> for the conversion * @return Java object converted to required class type if possible. @@ -426,7 +426,7 @@ throw Py.TypeError("array item must be unicode character"); } - + // relax to allow mixing with PyString, integers private static int getCodePointOrInt(PyObject obj) { if (obj instanceof PyUnicode) { @@ -444,14 +444,14 @@ return -1; } } - + /** * Append new value x to the end of the array. - * + * * @param value * item to be appended to the array */ - + public void append(PyObject value) { // Currently, this is asymmetric with extend, which // *will* do conversions like append(5.0) to an int array. @@ -497,7 +497,7 @@ /** * Implementation of <em>Cloneable</em> interface. - * + * * @return copy of current PyArray */ public Object clone() { @@ -507,7 +507,7 @@ /** * Converts a character code for the array type to a Java <code>Class</code>. * <p /> - * + * * The following character codes and their native types are supported:<br /> * <table> * <tr> @@ -548,10 +548,10 @@ * </tr> * </table> * <p /> - * + * * @param type * character code for the array type - * + * * @return <code>Class</code> of the native type */ @@ -609,7 +609,7 @@ else return cls.getName(); } - + @ExposedMethod public final int array_count(PyObject value) { // note: cpython does not raise type errors based on item type; @@ -634,7 +634,7 @@ } /** * Return the number of occurrences of x in the array. - * + * * @param value * instances of the value to be counted * @return number of time value was found in the array. @@ -645,7 +645,7 @@ /** * Delete the element at position <em>i</em> from the array - * + * * @param i * index of the item to be deleted from the array */ @@ -658,7 +658,7 @@ /** * Delete the slice defined by <em>start</em>, <em>stop</em> and * <em>step</em> from the array. - * + * * @param start * starting index of slice * @param stop @@ -681,7 +681,7 @@ } } } - + @ExposedMethod public final void array_extend(PyObject iterable){ extendInternal(iterable); @@ -694,7 +694,7 @@ * iterable and its elements must be the right type to be appended to the * array. Changed in version 2.4: Formerly, the argument could only be * another array. - * + * * @param iterable * iterable object used to extend the array */ @@ -707,12 +707,12 @@ * Handles specific cases of <em>iterable</em> being PyStrings or * PyArrays. Default behaviour is to defer to * {@link #extendInternalIter(PyObject) extendInternalIter } - * + * * @param iterable * object of type PyString, PyArray or any object that can be * iterated over. */ - + private void extendInternal(PyObject iterable) { if (iterable instanceof PyUnicode) { if ("u".equals(typecode)) { @@ -737,7 +737,7 @@ /** * Internal extend function to process iterable objects. - * + * * @param iterable * any object that can be iterated over. */ @@ -774,7 +774,7 @@ } } } - + private void extendArray(int[] items) { int last = delegate.getSize(); delegate.ensureCapacity(last + items.length); @@ -783,12 +783,12 @@ delegate.size++; } } - + @ExposedMethod public final void array_fromfile(PyObject f, int count){ fromfile(f, count); } - + /** * Read <em>count</em> items (as machine values) from the file object * <em>f</em> and append them to the end of the array. If less than @@ -796,7 +796,7 @@ * that were available are still inserted into the array. <em>f</em> must * be a real built-in file object; something else with a read() method won't * do. - * + * * @param f * Python builtin file object to retrieve data * @param count @@ -825,7 +825,7 @@ + Integer.toString(readcount) + " actually read"); } } - + @ExposedMethod public final void array_fromlist(PyObject obj){ fromlist(obj); @@ -834,7 +834,7 @@ /** * Append items from the list. This is equivalent to "for x in list: * a.append(x)"except that if there is a type error, the array is unchanged. - * + * * @param obj * input list object that will be appended to the array */ @@ -857,12 +857,12 @@ /** * Generic stream reader to read the entire contents of a stream into the * array. - * + * * @param is * InputStream to source the data from - * + * * @return number of primitives successfully read - * + * * @throws IOException * @throws EOFException */ @@ -873,14 +873,14 @@ /** * Generic stream reader to read <em>count</em> primitive types from a * stream into the array. - * + * * @param is * InputStream to source the data from * @param count * number of primitive types to read from the stream - * + * * @return number of primitives successfully read - * + * * @throws IOException * @throws EOFException */ @@ -948,7 +948,7 @@ * Appends items from the string, interpreting the string as an array of * machine values (as if it had been read from a file using the * {@link #fromfile(PyObject, int) fromfile()} method). - * + * * @param input * string of bytes containing array data */ @@ -990,7 +990,7 @@ /** * Get the element at position <em>i</em> from the array - * + * * @param i * index of the item to be retrieved from the array */ @@ -1003,7 +1003,7 @@ /** * Return the internal Java array storage of the PyArray instance - * + * * @return the <code>Array</code> store. */ public Object getArray() throws PyIgnoreMethodTag { @@ -1013,17 +1013,17 @@ /** * Getter for the storage size of the array's type. * <p /> - * + * * The sizes returned by this method represent the number of bytes used to * store the type. In the case of streams, this is the number of bytes * written to, or read from a stream. For memory this value is the * <em>minimum</em> number of bytes required to store the type. * <p /> - * + * * This method is used by other methods to define read/write quanta from * strings and streams. * <p /> - * + * * Values returned are:<br /> * <table> * <tr> @@ -1063,7 +1063,7 @@ * <td>8</td> * </tr> * </table> - * + * * @return number of bytes used to store array type. */ @ExposedGet(name = "itemsize") @@ -1093,7 +1093,7 @@ /** * Retrieve a slice from the array specified by the <em>start</em>, * <em>stop</em> and <em>step</em>. - * + * * @param start * start index of the slice * @param stop @@ -1124,14 +1124,14 @@ * Getter for the type code of the array. * {@link #char2class(char) char2class} describes the possible type codes * and their meaning. - * + * * @return single character type code for the array */ @ExposedGet(name = "typecode") public String getTypecode() { return typecode; } - + @ExposedMethod public final int array_index(PyObject value){ int index = indexInternal(value); @@ -1144,7 +1144,7 @@ /** * Return the smallest <em>i</em> such that <em>i</em> is the index of * the first occurrence of <em>value</em> in the array. - * + * * @param value * value to find the index of * @return index of the first occurance of <em>value</em> @@ -1156,7 +1156,7 @@ /** * Return the smallest <em>i</em> such that <em>i</em> is the index of * the first occurrence of <em>value</em> in the array. - * + * * @param value * value to find the index of * @return index of the first occurance of <em>value</em> @@ -1181,7 +1181,7 @@ } return -1; } - + @ExposedMethod public final void array_insert(int index, PyObject value){ insert(index, value); @@ -1191,7 +1191,7 @@ * Insert a new item with value <em>value</em> in the array before * position <em>index</em>. Negative values are treated as being relative * to the end of the array. - * + * * @param index * insert position * @param value @@ -1209,7 +1209,7 @@ Array.set(data, index, Py.tojava(value, type)); } } - + @ExposedMethod(defaults="-1") public final PyObject array_pop(int i){ PyObject val = pop(i); @@ -1232,7 +1232,7 @@ * Removes the item with the index <em>index</em> from the array and * returns it. The optional argument defaults to -1, so that by default the * last item is removed and returned. - * + * * @param index * array location to be popped from the array * @return array element popped from index @@ -1249,7 +1249,7 @@ delegate.remove(index); return ret; } - + @ExposedMethod public final void array_remove(PyObject value){ remove(value); @@ -1257,7 +1257,7 @@ /** * Remove the first occurrence of <em>value</em> from the array. - * + * * @param value * array value to be removed */ @@ -1273,7 +1273,7 @@ /** * Repeat the array <em>count</em> times. - * + * * @param count * number of times to repeat the array * @return A new PyArray object containing the source object repeated @@ -1289,7 +1289,7 @@ } return ret; } - + @ExposedMethod public final void array_reverse(){ reverse(); @@ -1297,7 +1297,7 @@ /** * Reverse the elements in the array - * + * */ public void reverse() { // build a new reversed array and set this.data to it when done @@ -1315,10 +1315,10 @@ * {@link AbstractArray#ensureCapacity(int) AbstractArray.ensureCapacity()} * for ways to extend capacity. * <p /> - * + * * This code specifically checks for overflows of the integral types: byte, * short, int and long. - * + * * @param i * index of the element to be set * @param value @@ -1328,8 +1328,8 @@ if ("u".equals(typecode)) { Array.setInt(data, i, getCodePoint(value)); return; - } - + } + if(type == Byte.TYPE) { long val; try { @@ -1401,15 +1401,15 @@ throw Py.TypeError("Type not compatible with array type"); } } - + public void set(int i, char value) { if ("c".equals(typecode) || type == Integer.TYPE || type == Long.TYPE) { Array.setChar(data, i, value); } else { throw Py.TypeError("Type not compatible with array type"); - } + } } - + private boolean isSigned() { return typecode.length() == 1 && typecode.equals(typecode.toUpperCase()); } @@ -1419,7 +1419,7 @@ * <code>byte</code> and <code>char</code> types) or PyArray. If a * PyArray, its type must be convertible into the type of the target * PyArray. - * + * * @param start * start index of the delete slice * @param stop @@ -1486,12 +1486,12 @@ } } } - + @ExposedMethod public final void array_tofile(PyObject f){ tofile(f); } - + @ExposedMethod public void array_write(PyObject f){ tofile(f); @@ -1499,7 +1499,7 @@ /** * Write all items (as machine values) to the file object <em>f</em>. - * + * * @param f * Python builtin file object to write data */ @@ -1521,7 +1521,7 @@ /** * Convert the array to an ordinary list with the same items. - * + * * @return array contents as a list */ public PyObject tolist() { @@ -1542,12 +1542,12 @@ /** * Generic stream writer to write the entire contents of the array to the * stream as primitive types. - * + * * @param os * OutputStream to sink the array data to - * + * * @return number of primitives successfully written - * + * * @throws IOException */ private int toStream(OutputStream os) throws IOException { @@ -1581,7 +1581,7 @@ } return dos.size(); } - + @ExposedMethod public final PyObject array_tostring(){ return new PyString(tostring()); @@ -1610,10 +1610,10 @@ int[] codepoints = new int[len]; for(int i = 0; i < len; i++) codepoints[i] = Array.getInt(data, i); - return new String(codepoints, 0, codepoints.length); + return new String(codepoints, 0, codepoints.length); } - - + + @ExposedMethod public final PyObject array_tounicode() { return new PyUnicode(tounicode()); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-23 00:18:20
|
Revision: 5604 http://jython.svn.sourceforge.net/jython/?rev=5604&view=rev Author: cgroves Date: 2008-11-23 00:18:15 +0000 (Sun, 23 Nov 2008) Log Message: ----------- Assume any instance of PySequence has an accurate __len__. See http://www.nabble.com/PySequenceList-and-fastSequence-td14977175.html Modified Paths: -------------- trunk/jython/src/org/python/core/PySequence.java Modified: trunk/jython/src/org/python/core/PySequence.java =================================================================== --- trunk/jython/src/org/python/core/PySequence.java 2008-11-22 23:30:45 UTC (rev 5603) +++ trunk/jython/src/org/python/core/PySequence.java 2008-11-23 00:18:15 UTC (rev 5604) @@ -4,12 +4,12 @@ /** * The abstract superclass of PyObjects that implements a Sequence. Minimize the work in creating * such objects. - * + * * Method names are designed to make it possible for subclasses of PySequence to implement * java.util.List. - * + * * Subclasses must also implement get, getslice, and repeat methods. - * + * * Subclasses that are mutable should also implement: set, setslice, del, and delRange. */ public abstract class PySequence extends PyObject { @@ -19,7 +19,7 @@ */ public PySequence() {} public int gListAllocatedStatus = -1; - + protected PySequence(PyType type) { super(type); } @@ -34,7 +34,7 @@ /** * Returns a range of elements from the sequence. - * + * * @param start * the position of the first element. * @param stop @@ -47,7 +47,7 @@ /** * Repeats the given sequence. - * + * * @param count * the number of times to repeat the sequence. * @return this sequence repeated count times. @@ -57,7 +57,7 @@ // These methods only apply to mutable sequences /** * Sets the given element of the sequence. - * + * * @param index * index of the element to set. * @param value @@ -217,9 +217,9 @@ } // Return a copy of a sequence where the __len__() method is - // telling the thruth. + // telling the truth. protected static PyObject fastSequence(PyObject seq, String msg) { - if(seq instanceof PyList || seq instanceof PyTuple) { + if(seq instanceof PySequence) { return seq; } PyList list = new PyList(); @@ -430,7 +430,7 @@ /** * Return sequence-specific error messages suitable for substitution. - * + * * {0} is the op name. {1} is the left operand type. {2} is the right operand type. */ protected String unsupportedopMessage(String op, PyObject o2) { @@ -442,7 +442,7 @@ /** * Return sequence-specific error messages suitable for substitution. - * + * * {0} is the op name. {1} is the left operand type. {2} is the right operand type. */ protected String runsupportedopMessage(String op, PyObject o2) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-22 23:30:49
|
Revision: 5603 http://jython.svn.sourceforge.net/jython/?rev=5603&view=rev Author: pjenvey Date: 2008-11-22 23:30:45 +0000 (Sat, 22 Nov 2008) Log Message: ----------- o fix help -- our new isatty support confused it into using a real pager o support $py.class in ispackage Modified Paths: -------------- trunk/jython/Lib/pydoc.py Modified: trunk/jython/Lib/pydoc.py =================================================================== --- trunk/jython/Lib/pydoc.py 2008-11-22 23:27:27 UTC (rev 5602) +++ trunk/jython/Lib/pydoc.py 2008-11-22 23:30:45 UTC (rev 5603) @@ -183,7 +183,7 @@ def ispackage(path): """Guess whether a path refers to a package directory.""" if os.path.isdir(path): - for ext in ('.py', '.pyc', '.pyo'): + for ext in ('.py', '.pyc', '.pyo', '$py.class'): if os.path.isfile(os.path.join(path, '__init__' + ext)): return True return False @@ -1300,6 +1300,8 @@ def getpager(): """Decide what method to use for paging through text.""" + if sys.platform.startswith('java'): + return plainpager if type(sys.stdout) is not types.FileType: return plainpager if not sys.stdin.isatty() or not sys.stdout.isatty(): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-22 23:27:32
|
Revision: 5602 http://jython.svn.sourceforge.net/jython/?rev=5602&view=rev Author: pjenvey Date: 2008-11-22 23:27:27 +0000 (Sat, 22 Nov 2008) Log Message: ----------- from: http://svn.python.org/projects/python/branches/release25-maint/Lib/pydoc.py@54366 Added Paths: ----------- trunk/jython/Lib/pydoc.py Added: trunk/jython/Lib/pydoc.py =================================================================== --- trunk/jython/Lib/pydoc.py (rev 0) +++ trunk/jython/Lib/pydoc.py 2008-11-22 23:27:27 UTC (rev 5602) @@ -0,0 +1,2255 @@ +#!/usr/bin/env python +# -*- coding: Latin-1 -*- +"""Generate Python documentation in HTML or text for interactive use. + +In the Python interpreter, do "from pydoc import help" to provide online +help. Calling help(thing) on a Python object documents the object. + +Or, at the shell command line outside of Python: + +Run "pydoc <name>" to show documentation on something. <name> may be +the name of a function, module, package, or a dotted reference to a +class or function within a module or module in a package. If the +argument contains a path segment delimiter (e.g. slash on Unix, +backslash on Windows) it is treated as the path to a Python source file. + +Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines +of all available modules. + +Run "pydoc -p <port>" to start an HTTP server on a given port on the +local machine to generate documentation web pages. + +For platforms without a command line, "pydoc -g" starts the HTTP server +and also pops up a little window for controlling it. + +Run "pydoc -w <name>" to write out the HTML documentation for a module +to a file named "<name>.html". + +Module docs for core modules are assumed to be in + + http://www.python.org/doc/current/lib/ + +This can be overridden by setting the PYTHONDOCS environment variable +to a different URL or to a local directory containing the Library +Reference Manual pages. +""" + +__author__ = "Ka-Ping Yee <pi...@lf...>" +__date__ = "26 February 2001" + +__version__ = "$Revision: 54366 $" +__credits__ = """Guido van Rossum, for an excellent programming language. +Tommy Burnette, the original creator of manpy. +Paul Prescod, for all his work on onlinehelp. +Richard Chamberlain, for the first implementation of textdoc. +""" + +# Known bugs that can't be fixed here: +# - imp.load_module() cannot be prevented from clobbering existing +# loaded modules, so calling synopsis() on a binary module file +# changes the contents of any existing module with the same name. +# - If the __file__ attribute on a module is a relative path and +# the current directory is changed with os.chdir(), an incorrect +# path will be displayed. + +import sys, imp, os, re, types, inspect, __builtin__, pkgutil +from repr import Repr +from string import expandtabs, find, join, lower, split, strip, rfind, rstrip +try: + from collections import deque +except ImportError: + # Python 2.3 compatibility + class deque(list): + def popleft(self): + return self.pop(0) + +# --------------------------------------------------------- common routines + +def pathdirs(): + """Convert sys.path into a list of absolute, existing, unique paths.""" + dirs = [] + normdirs = [] + for dir in sys.path: + dir = os.path.abspath(dir or '.') + normdir = os.path.normcase(dir) + if normdir not in normdirs and os.path.isdir(dir): + dirs.append(dir) + normdirs.append(normdir) + return dirs + +def getdoc(object): + """Get the doc string or comments for an object.""" + result = inspect.getdoc(object) or inspect.getcomments(object) + return result and re.sub('^ *\n', '', rstrip(result)) or '' + +def splitdoc(doc): + """Split a doc string into a synopsis line (if any) and the rest.""" + lines = split(strip(doc), '\n') + if len(lines) == 1: + return lines[0], '' + elif len(lines) >= 2 and not rstrip(lines[1]): + return lines[0], join(lines[2:], '\n') + return '', join(lines, '\n') + +def classname(object, modname): + """Get a class name and qualify it with a module name if necessary.""" + name = object.__name__ + if object.__module__ != modname: + name = object.__module__ + '.' + name + return name + +def isdata(object): + """Check if an object is of a type that probably means it's data.""" + return not (inspect.ismodule(object) or inspect.isclass(object) or + inspect.isroutine(object) or inspect.isframe(object) or + inspect.istraceback(object) or inspect.iscode(object)) + +def replace(text, *pairs): + """Do a series of global replacements on a string.""" + while pairs: + text = join(split(text, pairs[0]), pairs[1]) + pairs = pairs[2:] + return text + +def cram(text, maxlen): + """Omit part of a string if needed to make it fit in a maximum length.""" + if len(text) > maxlen: + pre = max(0, (maxlen-3)//2) + post = max(0, maxlen-3-pre) + return text[:pre] + '...' + text[len(text)-post:] + return text + +_re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE) +def stripid(text): + """Remove the hexadecimal id from a Python object representation.""" + # The behaviour of %p is implementation-dependent in terms of case. + if _re_stripid.search(repr(Exception)): + return _re_stripid.sub(r'\1', text) + return text + +def _is_some_method(obj): + return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) + +def allmethods(cl): + methods = {} + for key, value in inspect.getmembers(cl, _is_some_method): + methods[key] = 1 + for base in cl.__bases__: + methods.update(allmethods(base)) # all your base are belong to us + for key in methods.keys(): + methods[key] = getattr(cl, key) + return methods + +def _split_list(s, predicate): + """Split sequence s via predicate, and return pair ([true], [false]). + + The return value is a 2-tuple of lists, + ([x for x in s if predicate(x)], + [x for x in s if not predicate(x)]) + """ + + yes = [] + no = [] + for x in s: + if predicate(x): + yes.append(x) + else: + no.append(x) + return yes, no + +def visiblename(name, all=None): + """Decide whether to show documentation on a variable.""" + # Certain special names are redundant. + if name in ('__builtins__', '__doc__', '__file__', '__path__', + '__module__', '__name__', '__slots__'): return 0 + # Private names are hidden, but special names are displayed. + if name.startswith('__') and name.endswith('__'): return 1 + if all is not None: + # only document that which the programmer exported in __all__ + return name in all + else: + return not name.startswith('_') + +def classify_class_attrs(object): + """Wrap inspect.classify_class_attrs, with fixup for data descriptors.""" + def fixup((name, kind, cls, value)): + if inspect.isdatadescriptor(value): + kind = 'data descriptor' + return name, kind, cls, value + return map(fixup, inspect.classify_class_attrs(object)) + +# ----------------------------------------------------- module manipulation + +def ispackage(path): + """Guess whether a path refers to a package directory.""" + if os.path.isdir(path): + for ext in ('.py', '.pyc', '.pyo'): + if os.path.isfile(os.path.join(path, '__init__' + ext)): + return True + return False + +def source_synopsis(file): + line = file.readline() + while line[:1] == '#' or not strip(line): + line = file.readline() + if not line: break + line = strip(line) + if line[:4] == 'r"""': line = line[1:] + if line[:3] == '"""': + line = line[3:] + if line[-1:] == '\\': line = line[:-1] + while not strip(line): + line = file.readline() + if not line: break + result = strip(split(line, '"""')[0]) + else: result = None + return result + +def synopsis(filename, cache={}): + """Get the one-line summary out of a module file.""" + mtime = os.stat(filename).st_mtime + lastupdate, result = cache.get(filename, (0, None)) + if lastupdate < mtime: + info = inspect.getmoduleinfo(filename) + try: + file = open(filename) + except IOError: + # module can't be opened, so skip it + return None + if info and 'b' in info[2]: # binary modules have to be imported + try: module = imp.load_module('__temp__', file, filename, info[1:]) + except: return None + result = (module.__doc__ or '').splitlines()[0] + del sys.modules['__temp__'] + else: # text modules can be directly examined + result = source_synopsis(file) + file.close() + cache[filename] = (mtime, result) + return result + +class ErrorDuringImport(Exception): + """Errors that occurred while trying to import something to document it.""" + def __init__(self, filename, (exc, value, tb)): + self.filename = filename + self.exc = exc + self.value = value + self.tb = tb + + def __str__(self): + exc = self.exc + if type(exc) is types.ClassType: + exc = exc.__name__ + return 'problem in %s - %s: %s' % (self.filename, exc, self.value) + +def importfile(path): + """Import a Python source file or compiled file given its path.""" + magic = imp.get_magic() + file = open(path, 'r') + if file.read(len(magic)) == magic: + kind = imp.PY_COMPILED + else: + kind = imp.PY_SOURCE + file.close() + filename = os.path.basename(path) + name, ext = os.path.splitext(filename) + file = open(path, 'r') + try: + module = imp.load_module(name, file, path, (ext, 'r', kind)) + except: + raise ErrorDuringImport(path, sys.exc_info()) + file.close() + return module + +def safeimport(path, forceload=0, cache={}): + """Import a module; handle errors; return None if the module isn't found. + + If the module *is* found but an exception occurs, it's wrapped in an + ErrorDuringImport exception and reraised. Unlike __import__, if a + package path is specified, the module at the end of the path is returned, + not the package at the beginning. If the optional 'forceload' argument + is 1, we reload the module from disk (unless it's a dynamic extension).""" + try: + # If forceload is 1 and the module has been previously loaded from + # disk, we always have to reload the module. Checking the file's + # mtime isn't good enough (e.g. the module could contain a class + # that inherits from another module that has changed). + if forceload and path in sys.modules: + if path not in sys.builtin_module_names: + # Avoid simply calling reload() because it leaves names in + # the currently loaded module lying around if they're not + # defined in the new source file. Instead, remove the + # module from sys.modules and re-import. Also remove any + # submodules because they won't appear in the newly loaded + # module's namespace if they're already in sys.modules. + subs = [m for m in sys.modules if m.startswith(path + '.')] + for key in [path] + subs: + # Prevent garbage collection. + cache[key] = sys.modules[key] + del sys.modules[key] + module = __import__(path) + except: + # Did the error occur before or after the module was found? + (exc, value, tb) = info = sys.exc_info() + if path in sys.modules: + # An error occurred while executing the imported module. + raise ErrorDuringImport(sys.modules[path].__file__, info) + elif exc is SyntaxError: + # A SyntaxError occurred before we could execute the module. + raise ErrorDuringImport(value.filename, info) + elif exc is ImportError and \ + split(lower(str(value)))[:2] == ['no', 'module']: + # The module was not found. + return None + else: + # Some other error occurred during the importing process. + raise ErrorDuringImport(path, sys.exc_info()) + for part in split(path, '.')[1:]: + try: module = getattr(module, part) + except AttributeError: return None + return module + +# ---------------------------------------------------- formatter base class + +class Doc: + def document(self, object, name=None, *args): + """Generate documentation for an object.""" + args = (object, name) + args + # 'try' clause is to attempt to handle the possibility that inspect + # identifies something in a way that pydoc itself has issues handling; + # think 'super' and how it is a descriptor (which raises the exception + # by lacking a __name__ attribute) and an instance. + if inspect.isgetsetdescriptor(object): return self.docdata(*args) + if inspect.ismemberdescriptor(object): return self.docdata(*args) + try: + if inspect.ismodule(object): return self.docmodule(*args) + if inspect.isclass(object): return self.docclass(*args) + if inspect.isroutine(object): return self.docroutine(*args) + except AttributeError: + pass + if isinstance(object, property): return self.docproperty(*args) + return self.docother(*args) + + def fail(self, object, name=None, *args): + """Raise an exception for unimplemented types.""" + message = "don't know how to document object%s of type %s" % ( + name and ' ' + repr(name), type(object).__name__) + raise TypeError, message + + docmodule = docclass = docroutine = docother = docproperty = docdata = fail + + def getdocloc(self, object): + """Return the location of module docs or None""" + + try: + file = inspect.getabsfile(object) + except TypeError: + file = '(built-in)' + + docloc = os.environ.get("PYTHONDOCS", + "http://www.python.org/doc/current/lib") + basedir = os.path.join(sys.exec_prefix, "lib", + "python"+sys.version[0:3]) + if (isinstance(object, type(os)) and + (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', + 'marshal', 'posix', 'signal', 'sys', + 'thread', 'zipimport') or + (file.startswith(basedir) and + not file.startswith(os.path.join(basedir, 'site-packages'))))): + htmlfile = "module-%s.html" % object.__name__ + if docloc.startswith("http://"): + docloc = "%s/%s" % (docloc.rstrip("/"), htmlfile) + else: + docloc = os.path.join(docloc, htmlfile) + else: + docloc = None + return docloc + +# -------------------------------------------- HTML documentation generator + +class HTMLRepr(Repr): + """Class for safely making an HTML representation of a Python object.""" + def __init__(self): + Repr.__init__(self) + self.maxlist = self.maxtuple = 20 + self.maxdict = 10 + self.maxstring = self.maxother = 100 + + def escape(self, text): + return replace(text, '&', '&', '<', '<', '>', '>') + + def repr(self, object): + return Repr.repr(self, object) + + def repr1(self, x, level): + if hasattr(type(x), '__name__'): + methodname = 'repr_' + join(split(type(x).__name__), '_') + if hasattr(self, methodname): + return getattr(self, methodname)(x, level) + return self.escape(cram(stripid(repr(x)), self.maxother)) + + def repr_string(self, x, level): + test = cram(x, self.maxstring) + testrepr = repr(test) + if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): + # Backslashes are only literal in the string and are never + # needed to make any special characters, so show a raw string. + return 'r' + testrepr[0] + self.escape(test) + testrepr[0] + return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)', + r'<font color="#c040c0">\1</font>', + self.escape(testrepr)) + + repr_str = repr_string + + def repr_instance(self, x, level): + try: + return self.escape(cram(stripid(repr(x)), self.maxstring)) + except: + return self.escape('<%s instance>' % x.__class__.__name__) + + repr_unicode = repr_string + +class HTMLDoc(Doc): + """Formatter class for HTML documentation.""" + + # ------------------------------------------- HTML formatting utilities + + _repr_instance = HTMLRepr() + repr = _repr_instance.repr + escape = _repr_instance.escape + + def page(self, title, contents): + """Format an HTML page.""" + return ''' +<!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> +<html><head><title>Python: %s</title> +</head><body bgcolor="#f0f0f8"> +%s +</body></html>''' % (title, contents) + + def heading(self, title, fgcol, bgcol, extras=''): + """Format a page heading.""" + return ''' +<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading"> +<tr bgcolor="%s"> +<td valign=bottom> <br> +<font color="%s" face="helvetica, arial"> <br>%s</font></td +><td align=right valign=bottom +><font color="%s" face="helvetica, arial">%s</font></td></tr></table> + ''' % (bgcol, fgcol, title, fgcol, extras or ' ') + + def section(self, title, fgcol, bgcol, contents, width=6, + prelude='', marginalia=None, gap=' '): + """Format a section with a heading.""" + if marginalia is None: + marginalia = '<tt>' + ' ' * width + '</tt>' + result = '''<p> +<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> +<tr bgcolor="%s"> +<td colspan=3 valign=bottom> <br> +<font color="%s" face="helvetica, arial">%s</font></td></tr> + ''' % (bgcol, fgcol, title) + if prelude: + result = result + ''' +<tr bgcolor="%s"><td rowspan=2>%s</td> +<td colspan=2>%s</td></tr> +<tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap) + else: + result = result + ''' +<tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap) + + return result + '\n<td width="100%%">%s</td></tr></table>' % contents + + def bigsection(self, title, *args): + """Format a section with a big heading.""" + title = '<big><strong>%s</strong></big>' % title + return self.section(title, *args) + + def preformat(self, text): + """Format literal preformatted text.""" + text = self.escape(expandtabs(text)) + return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', + ' ', ' ', '\n', '<br>\n') + + def multicolumn(self, list, format, cols=4): + """Format a list of items into a multi-column list.""" + result = '' + rows = (len(list)+cols-1)/cols + for col in range(cols): + result = result + '<td width="%d%%" valign=top>' % (100/cols) + for i in range(rows*col, rows*col+rows): + if i < len(list): + result = result + format(list[i]) + '<br>\n' + result = result + '</td>' + return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result + + def grey(self, text): return '<font color="#909090">%s</font>' % text + + def namelink(self, name, *dicts): + """Make a link for an identifier, given name-to-URL mappings.""" + for dict in dicts: + if name in dict: + return '<a href="%s">%s</a>' % (dict[name], name) + return name + + def classlink(self, object, modname): + """Make a link for a class.""" + name, module = object.__name__, sys.modules.get(object.__module__) + if hasattr(module, name) and getattr(module, name) is object: + return '<a href="%s.html#%s">%s</a>' % ( + module.__name__, name, classname(object, modname)) + return classname(object, modname) + + def modulelink(self, object): + """Make a link for a module.""" + return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__) + + def modpkglink(self, (name, path, ispackage, shadowed)): + """Make a link for a module or package to display in an index.""" + if shadowed: + return self.grey(name) + if path: + url = '%s.%s.html' % (path, name) + else: + url = '%s.html' % name + if ispackage: + text = '<strong>%s</strong> (package)' % name + else: + text = name + return '<a href="%s">%s</a>' % (url, text) + + def markup(self, text, escape=None, funcs={}, classes={}, methods={}): + """Mark up some plain text, given a context of symbols to look for. + Each context dictionary maps object names to anchor names.""" + escape = escape or self.escape + results = [] + here = 0 + pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' + r'RFC[- ]?(\d+)|' + r'PEP[- ]?(\d+)|' + r'(self\.)?(\w+))') + while True: + match = pattern.search(text, here) + if not match: break + start, end = match.span() + results.append(escape(text[here:start])) + + all, scheme, rfc, pep, selfdot, name = match.groups() + if scheme: + url = escape(all).replace('"', '"') + results.append('<a href="%s">%s</a>' % (url, url)) + elif rfc: + url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) + results.append('<a href="%s">%s</a>' % (url, escape(all))) + elif pep: + url = 'http://www.python.org/peps/pep-%04d.html' % int(pep) + results.append('<a href="%s">%s</a>' % (url, escape(all))) + elif text[end:end+1] == '(': + results.append(self.namelink(name, methods, funcs, classes)) + elif selfdot: + results.append('self.<strong>%s</strong>' % name) + else: + results.append(self.namelink(name, classes)) + here = end + results.append(escape(text[here:])) + return join(results, '') + + # ---------------------------------------------- type-specific routines + + def formattree(self, tree, modname, parent=None): + """Produce HTML for a class tree as given by inspect.getclasstree().""" + result = '' + for entry in tree: + if type(entry) is type(()): + c, bases = entry + result = result + '<dt><font face="helvetica, arial">' + result = result + self.classlink(c, modname) + if bases and bases != (parent,): + parents = [] + for base in bases: + parents.append(self.classlink(base, modname)) + result = result + '(' + join(parents, ', ') + ')' + result = result + '\n</font></dt>' + elif type(entry) is type([]): + result = result + '<dd>\n%s</dd>\n' % self.formattree( + entry, modname, c) + return '<dl>\n%s</dl>\n' % result + + def docmodule(self, object, name=None, mod=None, *ignored): + """Produce HTML documentation for a module object.""" + name = object.__name__ # ignore the passed-in name + try: + all = object.__all__ + except AttributeError: + all = None + parts = split(name, '.') + links = [] + for i in range(len(parts)-1): + links.append( + '<a href="%s.html"><font color="#ffffff">%s</font></a>' % + (join(parts[:i+1], '.'), parts[i])) + linkedname = join(links + parts[-1:], '.') + head = '<big><big><strong>%s</strong></big></big>' % linkedname + try: + path = inspect.getabsfile(object) + url = path + if sys.platform == 'win32': + import nturl2path + url = nturl2path.pathname2url(path) + filelink = '<a href="file:%s">%s</a>' % (url, path) + except TypeError: + filelink = '(built-in)' + info = [] + if hasattr(object, '__version__'): + version = str(object.__version__) + if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': + version = strip(version[11:-1]) + info.append('version %s' % self.escape(version)) + if hasattr(object, '__date__'): + info.append(self.escape(str(object.__date__))) + if info: + head = head + ' (%s)' % join(info, ', ') + docloc = self.getdocloc(object) + if docloc is not None: + docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals() + else: + docloc = '' + result = self.heading( + head, '#ffffff', '#7799ee', + '<a href=".">index</a><br>' + filelink + docloc) + + modules = inspect.getmembers(object, inspect.ismodule) + + classes, cdict = [], {} + for key, value in inspect.getmembers(object, inspect.isclass): + # if __all__ exists, believe it. Otherwise use old heuristic. + if (all is not None or + (inspect.getmodule(value) or object) is object): + if visiblename(key, all): + classes.append((key, value)) + cdict[key] = cdict[value] = '#' + key + for key, value in classes: + for base in value.__bases__: + key, modname = base.__name__, base.__module__ + module = sys.modules.get(modname) + if modname != name and module and hasattr(module, key): + if getattr(module, key) is base: + if not key in cdict: + cdict[key] = cdict[base] = modname + '.html#' + key + funcs, fdict = [], {} + for key, value in inspect.getmembers(object, inspect.isroutine): + # if __all__ exists, believe it. Otherwise use old heuristic. + if (all is not None or + inspect.isbuiltin(value) or inspect.getmodule(value) is object): + if visiblename(key, all): + funcs.append((key, value)) + fdict[key] = '#-' + key + if inspect.isfunction(value): fdict[value] = fdict[key] + data = [] + for key, value in inspect.getmembers(object, isdata): + if visiblename(key, all): + data.append((key, value)) + + doc = self.markup(getdoc(object), self.preformat, fdict, cdict) + doc = doc and '<tt>%s</tt>' % doc + result = result + '<p>%s</p>\n' % doc + + if hasattr(object, '__path__'): + modpkgs = [] + for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): + modpkgs.append((modname, name, ispkg, 0)) + modpkgs.sort() + contents = self.multicolumn(modpkgs, self.modpkglink) + result = result + self.bigsection( + 'Package Contents', '#ffffff', '#aa55cc', contents) + elif modules: + contents = self.multicolumn( + modules, lambda (key, value), s=self: s.modulelink(value)) + result = result + self.bigsection( + 'Modules', '#fffff', '#aa55cc', contents) + + if classes: + classlist = map(lambda (key, value): value, classes) + contents = [ + self.formattree(inspect.getclasstree(classlist, 1), name)] + for key, value in classes: + contents.append(self.document(value, key, name, fdict, cdict)) + result = result + self.bigsection( + 'Classes', '#ffffff', '#ee77aa', join(contents)) + if funcs: + contents = [] + for key, value in funcs: + contents.append(self.document(value, key, name, fdict, cdict)) + result = result + self.bigsection( + 'Functions', '#ffffff', '#eeaa77', join(contents)) + if data: + contents = [] + for key, value in data: + contents.append(self.document(value, key)) + result = result + self.bigsection( + 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n')) + if hasattr(object, '__author__'): + contents = self.markup(str(object.__author__), self.preformat) + result = result + self.bigsection( + 'Author', '#ffffff', '#7799ee', contents) + if hasattr(object, '__credits__'): + contents = self.markup(str(object.__credits__), self.preformat) + result = result + self.bigsection( + 'Credits', '#ffffff', '#7799ee', contents) + + return result + + def docclass(self, object, name=None, mod=None, funcs={}, classes={}, + *ignored): + """Produce HTML documentation for a class object.""" + realname = object.__name__ + name = name or realname + bases = object.__bases__ + + contents = [] + push = contents.append + + # Cute little class to pump out a horizontal rule between sections. + class HorizontalRule: + def __init__(self): + self.needone = 0 + def maybe(self): + if self.needone: + push('<hr>\n') + self.needone = 1 + hr = HorizontalRule() + + # List the mro, if non-trivial. + mro = deque(inspect.getmro(object)) + if len(mro) > 2: + hr.maybe() + push('<dl><dt>Method resolution order:</dt>\n') + for base in mro: + push('<dd>%s</dd>\n' % self.classlink(base, + object.__module__)) + push('</dl>\n') + + def spill(msg, attrs, predicate): + ok, attrs = _split_list(attrs, predicate) + if ok: + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: + push(self.document(getattr(object, name), name, mod, + funcs, classes, mdict, object)) + push('\n') + return attrs + + def spilldescriptors(msg, attrs, predicate): + ok, attrs = _split_list(attrs, predicate) + if ok: + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: + push(self._docdescriptor(name, value, mod)) + return attrs + + def spilldata(msg, attrs, predicate): + ok, attrs = _split_list(attrs, predicate) + if ok: + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: + base = self.docother(getattr(object, name), name, mod) + if callable(value) or inspect.isdatadescriptor(value): + doc = getattr(value, "__doc__", None) + else: + doc = None + if doc is None: + push('<dl><dt>%s</dl>\n' % base) + else: + doc = self.markup(getdoc(value), self.preformat, + funcs, classes, mdict) + doc = '<dd><tt>%s</tt>' % doc + push('<dl><dt>%s%s</dl>\n' % (base, doc)) + push('\n') + return attrs + + attrs = filter(lambda (name, kind, cls, value): visiblename(name), + classify_class_attrs(object)) + mdict = {} + for key, kind, homecls, value in attrs: + mdict[key] = anchor = '#' + name + '-' + key + value = getattr(object, key) + try: + # The value may not be hashable (e.g., a data attr with + # a dict or list value). + mdict[value] = anchor + except TypeError: + pass + + while attrs: + if mro: + thisclass = mro.popleft() + else: + thisclass = attrs[0][2] + attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) + + if thisclass is __builtin__.object: + attrs = inherited + continue + elif thisclass is object: + tag = 'defined here' + else: + tag = 'inherited from %s' % self.classlink(thisclass, + object.__module__) + tag += ':<br>\n' + + # Sort attrs by name. + try: + attrs.sort(key=lambda t: t[0]) + except TypeError: + attrs.sort(lambda t1, t2: cmp(t1[0], t2[0])) # 2.3 compat + + # Pump out the attrs, segregated by kind. + attrs = spill('Methods %s' % tag, attrs, + lambda t: t[1] == 'method') + attrs = spill('Class methods %s' % tag, attrs, + lambda t: t[1] == 'class method') + attrs = spill('Static methods %s' % tag, attrs, + lambda t: t[1] == 'static method') + attrs = spilldescriptors('Data descriptors %s' % tag, attrs, + lambda t: t[1] == 'data descriptor') + attrs = spilldata('Data and other attributes %s' % tag, attrs, + lambda t: t[1] == 'data') + assert attrs == [] + attrs = inherited + + contents = ''.join(contents) + + if name == realname: + title = '<a name="%s">class <strong>%s</strong></a>' % ( + name, realname) + else: + title = '<strong>%s</strong> = <a name="%s">class %s</a>' % ( + name, name, realname) + if bases: + parents = [] + for base in bases: + parents.append(self.classlink(base, object.__module__)) + title = title + '(%s)' % join(parents, ', ') + doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict) + doc = doc and '<tt>%s<br> </tt>' % doc + + return self.section(title, '#000000', '#ffc8d8', contents, 3, doc) + + def formatvalue(self, object): + """Format an argument default value as text.""" + return self.grey('=' + self.repr(object)) + + def docroutine(self, object, name=None, mod=None, + funcs={}, classes={}, methods={}, cl=None): + """Produce HTML documentation for a function or method object.""" + realname = object.__name__ + name = name or realname + anchor = (cl and cl.__name__ or '') + '-' + name + note = '' + skipdocs = 0 + if inspect.ismethod(object): + imclass = object.im_class + if cl: + if imclass is not cl: + note = ' from ' + self.classlink(imclass, mod) + else: + if object.im_self is not None: + note = ' method of %s instance' % self.classlink( + object.im_self.__class__, mod) + else: + note = ' unbound %s method' % self.classlink(imclass,mod) + object = object.im_func + + if name == realname: + title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname) + else: + if (cl and realname in cl.__dict__ and + cl.__dict__[realname] is object): + reallink = '<a href="#%s">%s</a>' % ( + cl.__name__ + '-' + realname, realname) + skipdocs = 1 + else: + reallink = realname + title = '<a name="%s"><strong>%s</strong></a> = %s' % ( + anchor, name, reallink) + if inspect.isfunction(object): + args, varargs, varkw, defaults = inspect.getargspec(object) + argspec = inspect.formatargspec( + args, varargs, varkw, defaults, formatvalue=self.formatvalue) + if realname == '<lambda>': + title = '<strong>%s</strong> <em>lambda</em> ' % name + argspec = argspec[1:-1] # remove parentheses + else: + argspec = '(...)' + + decl = title + argspec + (note and self.grey( + '<font face="helvetica, arial">%s</font>' % note)) + + if skipdocs: + return '<dl><dt>%s</dt></dl>\n' % decl + else: + doc = self.markup( + getdoc(object), self.preformat, funcs, classes, methods) + doc = doc and '<dd><tt>%s</tt></dd>' % doc + return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc) + + def _docdescriptor(self, name, value, mod): + results = [] + push = results.append + + if name: + push('<dl><dt><strong>%s</strong></dt>\n' % name) + if value.__doc__ is not None: + doc = self.markup(getdoc(value), self.preformat) + push('<dd><tt>%s</tt></dd>\n' % doc) + push('</dl>\n') + + return ''.join(results) + + def docproperty(self, object, name=None, mod=None, cl=None): + """Produce html documentation for a property.""" + return self._docdescriptor(name, object, mod) + + def docother(self, object, name=None, mod=None, *ignored): + """Produce HTML documentation for a data object.""" + lhs = name and '<strong>%s</strong> = ' % name or '' + return lhs + self.repr(object) + + def docdata(self, object, name=None, mod=None, cl=None): + """Produce html documentation for a data descriptor.""" + return self._docdescriptor(name, object, mod) + + def index(self, dir, shadowed=None): + """Generate an HTML index for a directory of modules.""" + modpkgs = [] + if shadowed is None: shadowed = {} + for importer, name, ispkg in pkgutil.iter_modules([dir]): + modpkgs.append((name, '', ispkg, name in shadowed)) + shadowed[name] = 1 + + modpkgs.sort() + contents = self.multicolumn(modpkgs, self.modpkglink) + return self.bigsection(dir, '#ffffff', '#ee77aa', contents) + +# -------------------------------------------- text documentation generator + +class TextRepr(Repr): + """Class for safely making a text representation of a Python object.""" + def __init__(self): + Repr.__init__(self) + self.maxlist = self.maxtuple = 20 + self.maxdict = 10 + self.maxstring = self.maxother = 100 + + def repr1(self, x, level): + if hasattr(type(x), '__name__'): + methodname = 'repr_' + join(split(type(x).__name__), '_') + if hasattr(self, methodname): + return getattr(self, methodname)(x, level) + return cram(stripid(repr(x)), self.maxother) + + def repr_string(self, x, level): + test = cram(x, self.maxstring) + testrepr = repr(test) + if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): + # Backslashes are only literal in the string and are never + # needed to make any special characters, so show a raw string. + return 'r' + testrepr[0] + test + testrepr[0] + return testrepr + + repr_str = repr_string + + def repr_instance(self, x, level): + try: + return cram(stripid(repr(x)), self.maxstring) + except: + return '<%s instance>' % x.__class__.__name__ + +class TextDoc(Doc): + """Formatter class for text documentation.""" + + # ------------------------------------------- text formatting utilities + + _repr_instance = TextRepr() + repr = _repr_instance.repr + + def bold(self, text): + """Format a string in bold by overstriking.""" + return join(map(lambda ch: ch + '\b' + ch, text), '') + + def indent(self, text, prefix=' '): + """Indent text by prepending a given prefix to each line.""" + if not text: return '' + lines = split(text, '\n') + lines = map(lambda line, prefix=prefix: prefix + line, lines) + if lines: lines[-1] = rstrip(lines[-1]) + return join(lines, '\n') + + def section(self, title, contents): + """Format a section with a given heading.""" + return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n' + + # ---------------------------------------------- type-specific routines + + def formattree(self, tree, modname, parent=None, prefix=''): + """Render in text a class tree as returned by inspect.getclasstree().""" + result = '' + for entry in tree: + if type(entry) is type(()): + c, bases = entry + result = result + prefix + classname(c, modname) + if bases and bases != (parent,): + parents = map(lambda c, m=modname: classname(c, m), bases) + result = result + '(%s)' % join(parents, ', ') + result = result + '\n' + elif type(entry) is type([]): + result = result + self.formattree( + entry, modname, c, prefix + ' ') + return result + + def docmodule(self, object, name=None, mod=None): + """Produce text documentation for a given module object.""" + name = object.__name__ # ignore the passed-in name + synop, desc = splitdoc(getdoc(object)) + result = self.section('NAME', name + (synop and ' - ' + synop)) + + try: + all = object.__all__ + except AttributeError: + all = None + + try: + file = inspect.getabsfile(object) + except TypeError: + file = '(built-in)' + result = result + self.section('FILE', file) + + docloc = self.getdocloc(object) + if docloc is not None: + result = result + self.section('MODULE DOCS', docloc) + + if desc: + result = result + self.section('DESCRIPTION', desc) + + classes = [] + for key, value in inspect.getmembers(object, inspect.isclass): + # if __all__ exists, believe it. Otherwise use old heuristic. + if (all is not None + or (inspect.getmodule(value) or object) is object): + if visiblename(key, all): + classes.append((key, value)) + funcs = [] + for key, value in inspect.getmembers(object, inspect.isroutine): + # if __all__ exists, believe it. Otherwise use old heuristic. + if (all is not None or + inspect.isbuiltin(value) or inspect.getmodule(value) is object): + if visiblename(key, all): + funcs.append((key, value)) + data = [] + for key, value in inspect.getmembers(object, isdata): + if visiblename(key, all): + data.append((key, value)) + + if hasattr(object, '__path__'): + modpkgs = [] + for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): + if ispkg: + modpkgs.append(modname + ' (package)') + else: + modpkgs.append(modname) + + modpkgs.sort() + result = result + self.section( + 'PACKAGE CONTENTS', join(modpkgs, '\n')) + + if classes: + classlist = map(lambda (key, value): value, classes) + contents = [self.formattree( + inspect.getclasstree(classlist, 1), name)] + for key, value in classes: + contents.append(self.document(value, key, name)) + result = result + self.section('CLASSES', join(contents, '\n')) + + if funcs: + contents = [] + for key, value in funcs: + contents.append(self.document(value, key, name)) + result = result + self.section('FUNCTIONS', join(contents, '\n')) + + if data: + contents = [] + for key, value in data: + contents.append(self.docother(value, key, name, maxlen=70)) + result = result + self.section('DATA', join(contents, '\n')) + + if hasattr(object, '__version__'): + version = str(object.__version__) + if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': + version = strip(version[11:-1]) + result = result + self.section('VERSION', version) + if hasattr(object, '__date__'): + result = result + self.section('DATE', str(object.__date__)) + if hasattr(object, '__author__'): + result = result + self.section('AUTHOR', str(object.__author__)) + if hasattr(object, '__credits__'): + result = result + self.section('CREDITS', str(object.__credits__)) + return result + + def docclass(self, object, name=None, mod=None): + """Produce text documentation for a given class object.""" + realname = object.__name__ + name = name or realname + bases = object.__bases__ + + def makename(c, m=object.__module__): + return classname(c, m) + + if name == realname: + title = 'class ' + self.bold(realname) + else: + title = self.bold(name) + ' = class ' + realname + if bases: + parents = map(makename, bases) + title = title + '(%s)' % join(parents, ', ') + + doc = getdoc(object) + contents = doc and [doc + '\n'] or [] + push = contents.append + + # List the mro, if non-trivial. + mro = deque(inspect.getmro(object)) + if len(mro) > 2: + push("Method resolution order:") + for base in mro: + push(' ' + makename(base)) + push('') + + # Cute little class to pump out a horizontal rule between sections. + class HorizontalRule: + def __init__(self): + self.needone = 0 + def maybe(self): + if self.needone: + push('-' * 70) + self.needone = 1 + hr = HorizontalRule() + + def spill(msg, attrs, predicate): + ok, attrs = _split_list(attrs, predicate) + if ok: + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: + push(self.document(getattr(object, name), + name, mod, object)) + return attrs + + def spilldescriptors(msg, attrs, predicate): + ok, attrs = _split_list(attrs, predicate) + if ok: + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: + push(self._docdescriptor(name, value, mod)) + return attrs + + def spilldata(msg, attrs, predicate): + ok, attrs = _split_list(attrs, predicate) + if ok: + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: + if callable(value) or inspect.isdatadescriptor(value): + doc = getdoc(value) + else: + doc = None + push(self.docother(getattr(object, name), + name, mod, maxlen=70, doc=doc) + '\n') + return attrs + + attrs = filter(lambda (name, kind, cls, value): visiblename(name), + classify_class_attrs(object)) + while attrs: + if mro: + thisclass = mro.popleft() + else: + thisclass = attrs[0][2] + attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) + + if thisclass is __builtin__.object: + attrs = inherited + continue + elif thisclass is object: + tag = "defined here" + else: + tag = "inherited from %s" % classname(thisclass, + object.__module__) + filter(lambda t: not t[0].startswith('_'), attrs) + + # Sort attrs by name. + attrs.sort() + + # Pump out the attrs, segregated by kind. + attrs = spill("Methods %s:\n" % tag, attrs, + lambda t: t[1] == 'method') + attrs = spill("Class methods %s:\n" % tag, attrs, + lambda t: t[1] == 'class method') + attrs = spill("Static methods %s:\n" % tag, attrs, + lambda t: t[1] == 'static method') + attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs, + lambda t: t[1] == 'data descriptor') + attrs = spilldata("Data and other attributes %s:\n" % tag, attrs, + lambda t: t[1] == 'data') + assert attrs == [] + attrs = inherited + + contents = '\n'.join(contents) + if not contents: + return title + '\n' + return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n' + + def formatvalue(self, object): + """Format an argument default value as text.""" + return '=' + self.repr(object) + + def docroutine(self, object, name=None, mod=None, cl=None): + """Produce text documentation for a function or method object.""" + realname = object.__name__ + name = name or realname + note = '' + skipdocs = 0 + if inspect.ismethod(object): + imclass = object.im_class + if cl: + if imclass is not cl: + note = ' from ' + classname(imclass, mod) + else: + if object.im_self is not None: + note = ' method of %s instance' % classname( + object.im_self.__class__, mod) + else: + note = ' unbound %s method' % classname(imclass,mod) + object = object.im_func + + if name == realname: + title = self.bold(realname) + else: + if (cl and realname in cl.__dict__ and + cl.__dict__[realname] is object): + skipdocs = 1 + title = self.bold(name) + ' = ' + realname + if inspect.isfunction(object): + args, varargs, varkw, defaults = inspect.getargspec(object) + argspec = inspect.formatargspec( + args, varargs, varkw, defaults, formatvalue=self.formatvalue) + if realname == '<lambda>': + title = self.bold(name) + ' lambda ' + argspec = argspec[1:-1] # remove parentheses + else: + argspec = '(...)' + decl = title + argspec + note + + if skipdocs: + return decl + '\n' + else: + doc = getdoc(object) or '' + return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n') + + def _docdescriptor(self, name, value, mod): + results = [] + push = results.append + + if name: + push(self.bold(name)) + push('\n') + doc = getdoc(value) or '' + if doc: + push(self.indent(doc)) + push('\n') + return ''.join(results) + + def docproperty(self, object, name=None, mod=None, cl=None): + """Produce text documentation for a property.""" + return self._docdescriptor(name, object, mod) + + def docdata(self, object, name=None, mod=None, cl=None): + """Produce text documentation for a data descriptor.""" + return self._docdescriptor(name, object, mod) + + def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None): + """Produce text documentation for a data object.""" + repr = self.repr(object) + if maxlen: + line = (name and name + ' = ' or '') + repr + chop = maxlen - len(line) + if chop < 0: repr = repr[:chop] + '...' + line = (name and self.bold(name) + ' = ' or '') + repr + if doc is not None: + line += '\n' + self.indent(str(doc)) + return line + +# --------------------------------------------------------- user interfaces + +def pager(text): + """The first time this is called, determine what kind of pager to use.""" + global pager + pager = getpager() + pager(text) + +def getpager(): + """Decide what method to use for paging through text.""" + if type(sys.stdout) is not types.FileType: + return plainpager + if not sys.stdin.isatty() or not sys.stdout.isatty(): + return plainpager + if 'PAGER' in os.environ: + if sys.platform == 'win32': # pipes completely broken in Windows + return lambda text: tempfilepager(plain(text), os.environ['PAGER']) + elif os.environ.get('TERM') in ('dumb', 'emacs'): + return lambda text: pipepager(plain(text), os.environ['PAGER']) + else: + return lambda text: pipepager(text, os.environ['PAGER']) + if os.environ.get('TERM') in ('dumb', 'emacs'): + return plainpager + if sys.platform == 'win32' or sys.platform.startswith('os2'): + return lambda text: tempfilepager(plain(text), 'more <') + if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: + return lambda text: pipepager(text, 'less') + + import tempfile + (fd, filename) = tempfile.mkstemp() + os.close(fd) + try: + if hasattr(os, 'system') and os.system('more %s' % filename) == 0: + return lambda text: pipepager(text, 'more') + else: + return ttypager + finally: + os.unlink(filename) + +def plain(text): + """Remove boldface formatting from text.""" + return re.sub('.\b', '', text) + +def pipepager(text, cmd): + """Page through text by feeding it to another program.""" + pipe = os.popen(cmd, 'w') + try: + pipe.write(text) + pipe.close() + except IOError: + pass # Ignore broken pipes caused by quitting the pager program. + +def tempfilepager(text, cmd): + """Page through text by invoking a program on a temporary file.""" + import tempfile + filename = tempfile.mktemp() + file = open(filename, 'w') + file.write(text) + file.close() + try: + os.system(cmd + ' ' + filename) + finally: + os.unlink(filename) + +def ttypager(text): + """Page through text on a text terminal.""" + lines = split(plain(text), '\n') + try: + import tty + fd = sys.stdin.fileno() + old = tty.tcgetattr(fd) + tty.setcbreak(fd) + getchar = lambda: sys.stdin.read(1) + except (ImportError, AttributeError): + tty = None + getchar = lambda: sys.stdin.readline()[:-1][:1] + + try: + r = inc = os.environ.get('LINES', 25) - 1 + sys.stdout.write(join(lines[:inc], '\n') + '\n') + while lines[r:]: + sys.stdout.write('-- more --') + sys.stdout.flush() + c = getchar() + + if c in ('q', 'Q'): + sys.stdout.write('\r \r') + break + elif c in ('\r', '\n'): + sys.stdout.write('\r \r' + lines[r] + '\n') + r = r + 1 + continue + if c in ('b', 'B', '\x1b'): + r = r - inc - inc + if r < 0: r = 0 + sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n') + r = r + inc + + finally: + if tty: + tty.tcsetattr(fd, tty.TCSAFLUSH, old) + +def plainpager(text): + """Simply print unformatted text. This is the ultimate fallback.""" + sys.stdout.write(plain(text)) + +def describe(thing): + """Produce a short description of the given thing.""" + if inspect.ismodule(thing): + if thing.__name__ in sys.builtin_module_names: + return 'built-in module ' + thing.__name__ + if hasattr(thing, '__path__'): + return 'package ' + thing.__name__ + else: + return 'module ' + thing.__name__ + if inspect.isbuiltin(thing): + return 'built-in function ' + thing.__name__ + if inspect.isgetsetdescriptor(thing): + return 'getset descriptor %s.%s.%s' % ( + thing.__objclass__.__module__, thing.__objclass__.__name__, + thing.__name__) + if inspect.ismemberdescriptor(thing): + return 'member descriptor %s.%s.%s' % ( + thing.__objclass__.__module__, thing.__objclass__.__name__, + thing.__name__) + if inspect.isclass(thing): + return 'class ' + thing.__name__ + if inspect.isfunction(thing): + return 'function ' + thing.__name__ + if inspect.ismethod(thing): + return 'method ' + thing.__name__ + if type(thing) is types.InstanceType: + return 'instance of ' + thing.__class__.__name__ + return type(thing).__name__ + +def locate(path, forceload=0): + """Locate an object by name or dotted path, importing as necessary.""" + parts = [part for part in split(path, '.') if part] + module, n = None, 0 + while n < len(parts): + nextmodule = safeimport(join(parts[:n+1], '.'), forceload) + if nextmodule: module, n = nextmodule, n + 1 + else: break + if module: + object = module + for part in parts[n:]: + try: object = getattr(object, part) + except AttributeError: return None + return object + else: + if hasattr(__builtin__, path): + return getattr(__builtin__, path) + +# --------------------------------------- interactive interpreter interface + +text = TextDoc() +html = HTMLDoc() + +def resolve(thing, forceload=0): + """Given an object or a path to an object, get the object and its name.""" + if isinstance(thing, str): + object = locate(thing, forceload) + if not object: + raise ImportError, 'no Python documentation found for %r' % thing + return object, thing + else: + return thing, getattr(thing, '__name__', None) + +def doc(thing, title='Python Library Documentation: %s', forceload=0): + """Display text documentation, given an object or a path to an object.""" + try: + object, name = resolve(thing, forceload) + desc = describe(object) + module = inspect.getmodule(object) + if name and '.' in name: + desc += ' in ' + name[:name.rfind('.')] + elif module and module is not object: + desc += ' in module ' + module.__name__ + if not (inspect.ismodule(object) or + inspect.isclass(object) or + inspect.isroutine(object) or + inspect.isgetsetdescriptor(object) or + inspect.ismemberdescriptor(object) or + isinstance(object, property)): + # If the passed object is a piece of data or an instance, + # document its available methods instead of its value. + object = type(object) + desc += ' object' + pager(title % desc + '\n\n' + text.document(object, name)) + except (ImportError, ErrorDuringImport), value: + print value + +def writedoc(thing, forceload=0): + """Write HTML documentation to a file in the current directory.""" + try: + object, name = resolve(thing, forceload) + page = html.page(describe(object), html.document(object, name)) + file = open(name + '.html', 'w') +... [truncated message content] |
From: <pj...@us...> - 2008-11-22 23:23:56
|
Revision: 5601 http://jython.svn.sourceforge.net/jython/?rev=5601&view=rev Author: pjenvey Date: 2008-11-22 23:23:48 +0000 (Sat, 22 Nov 2008) Log Message: ----------- use the compiled filename for __file__ when appropriate. make imp responsible for setting __file__ instead of the compiler being involved fixes #1138 Modified Paths: -------------- trunk/jython/Lib/inspect.py trunk/jython/Lib/test/test_chdir.py trunk/jython/Lib/test/test_import_jy.py trunk/jython/Lib/test/test_inspect.py trunk/jython/Lib/warnings.py trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/compiler/Module.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/imp.java trunk/jython/src/org/python/modules/imp.java Modified: trunk/jython/Lib/inspect.py =================================================================== --- trunk/jython/Lib/inspect.py 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/Lib/inspect.py 2008-11-22 23:23:48 UTC (rev 5601) @@ -383,6 +383,8 @@ filename = getfile(object) if string.lower(filename[-4:]) in ('.pyc', '.pyo'): filename = filename[:-4] + '.py' + elif filename.endswith('$py.class'): + filename = filename[:-9] + '.py' for suffix, mode, kind in imp.get_suffixes(): if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: # Looks like a binary file. We want to only return a text file. Modified: trunk/jython/Lib/test/test_chdir.py =================================================================== --- trunk/jython/Lib/test/test_chdir.py 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/Lib/test/test_chdir.py 2008-11-22 23:23:48 UTC (rev 5601) @@ -361,14 +361,8 @@ __import__(self.mod_name) self.assert_(self.mod_name in sys.modules) mod = sys.modules[self.mod_name] + self.assertEqual(mod.__file__, self.mod_name + COMPILED_SUFFIX) - # XXX: Jython's import has a bug where it doesn't use the - # $py.class filename when it exists along with the .py file - if sys.platform.startswith('java'): - self.assertEqual(mod.__file__, self.mod_name + '.py') - else: - self.assertEqual(mod.__file__, self.mod_name + COMPILED_SUFFIX) - def test_compile_dest(self): py_compile.compile(self.basename1, self.basename1[:-3] + Modified: trunk/jython/Lib/test/test_import_jy.py =================================================================== --- trunk/jython/Lib/test/test_import_jy.py 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/Lib/test/test_import_jy.py 2008-11-22 23:23:48 UTC (rev 5601) @@ -73,14 +73,8 @@ fp.close() module_obj = __import__('foo.test') self.assertEquals(module_obj.test.baz, 'testtest') - # XXX: Jython's import has a bug where it doesn't use the - # $py.class filename when it exists along with the .py file - if sys.platform.startswith('java'): - self.assertEqual(module_obj.test.init_file, - os.path.join('foo', '__init__.py')) - else: - self.assertEqual(module_obj.test.init_file, - os.path.join('foo', '__init__' + COMPILED_SUFFIX)) + self.assertEqual(module_obj.test.init_file, + os.path.join('foo', '__init__' + COMPILED_SUFFIX)) # Ensure a recompile of __init__$py.class wasn't triggered to # satisfy the abnormal import Modified: trunk/jython/Lib/test/test_inspect.py =================================================================== --- trunk/jython/Lib/test/test_inspect.py 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/Lib/test/test_inspect.py 2008-11-22 23:23:48 UTC (rev 5601) @@ -20,6 +20,8 @@ modfile = mod.__file__ if modfile.endswith(('c', 'o')): modfile = modfile[:-1] +elif modfile.endswith('$py.class'): + modfile = modfile[:-9] + '.py' import __builtin__ Modified: trunk/jython/Lib/warnings.py =================================================================== --- trunk/jython/Lib/warnings.py 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/Lib/warnings.py 2008-11-22 23:23:48 UTC (rev 5601) @@ -48,6 +48,8 @@ fnl = filename.lower() if fnl.endswith((".pyc", ".pyo")): filename = filename[:-1] + elif fnl.endswith("$py.class"): + filename = filename[:-9] + '.py' else: if module == "__main__": try: Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-11-22 23:23:48 UTC (rev 5601) @@ -303,12 +303,6 @@ visit(((Expr) suite.body[0]).value); code.invokevirtual("org/python/core/PyFrame", "setglobal", "(" +$str + $pyObj + ")V"); } - if (module.setFile) { - loadFrame(); - code.ldc("__file__"); - module.filename.get(code); - code.invokevirtual("org/python/core/PyFrame", "setglobal", "(" +$str + $pyObj + ")V"); - } traverse(suite); return null; } Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/src/org/python/compiler/Module.java 2008-11-22 23:23:48 UTC (rev 5601) @@ -293,7 +293,6 @@ String sfilename; public Constant mainCode; public boolean linenumbers; - public boolean setFile=true; Future futures; Hashtable scopes; @@ -636,12 +635,10 @@ public static void compile(modType node, OutputStream ostream, String name, String filename, boolean linenumbers, boolean printResults, - boolean setFile, org.python.core.CompilerFlags cflags) throws Exception { Module module = new Module(name, filename, linenumbers); - module.setFile = setFile; if (cflags == null) { cflags = new CompilerFlags(); } @@ -649,7 +646,6 @@ new ScopesCompiler(module, module.scopes).parse(node); //Add __doc__ if it exists - //Add __file__ for filename (if it exists?) Constant main = module.PyCode(node, "<module>", false, null, false, printResults, 0, Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/src/org/python/core/Py.java 2008-11-22 23:23:48 UTC (rev 5601) @@ -1708,8 +1708,7 @@ return Py.java2py(node); } ByteArrayOutputStream ostream = new ByteArrayOutputStream(); - Module.compile(node, ostream, name, filename, linenumbers, - printResults, false, cflags); + Module.compile(node, ostream, name, filename, linenumbers, printResults, cflags); saveClassFile(name, ostream); Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/src/org/python/core/imp.java 2008-11-22 23:23:48 UTC (rev 5601) @@ -7,9 +7,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; import java.util.concurrent.locks.ReentrantLock; import org.python.core.util.FileUtil; @@ -22,9 +19,9 @@ private static final String UNKNOWN_SOURCEFILE = "<unknown>"; - public static final int APIVersion = 16; + public static final int APIVersion = 17; - //This should change to 0 for Python 2.7 and 3.0 see PEP 328 + // This should change to 0 for Python 2.7 and 3.0 see PEP 328 public static final int DEFAULT_LEVEL = -1; /** A non-empty fromlist for __import__'ing sub-modules. */ @@ -88,15 +85,15 @@ } } - static PyObject createFromPyClass(String name, InputStream fp, - boolean testing, String fileName) { + static PyObject createFromPyClass(String name, InputStream fp, boolean testing, + String sourceName, String compiledName) { byte[] data = readCode(name, fp, testing); if (testing && data == null) { return null; } PyCode code; try { - code = BytecodeLoader.makeCode(name + "$py", data, fileName); + code = BytecodeLoader.makeCode(name + "$py", data, sourceName); } catch (Throwable t) { if (testing) { return null; @@ -105,14 +102,14 @@ } } - Py.writeComment(IMPORT_LOG, "'" + name + "' as " + fileName); + Py.writeComment(IMPORT_LOG, String.format("import %s # precompiled from %s", name, + compiledName)); - return createFromCode(name, code, fileName); + return createFromCode(name, code, compiledName); } public static byte[] readCode(String name, InputStream fp, boolean testing) { byte[] data = readBytes(fp); - int n = data.length; int api; try { @@ -209,7 +206,6 @@ filename, true, false, - true, null); return ofp.toByteArray(); } catch(Throwable t) { @@ -256,6 +252,15 @@ if (c instanceof PyTableCode) { code = (PyTableCode) c; } + + if (moduleLocation != null) { + module.__setattr__("__file__", new PyString(moduleLocation)); + } else if (module.__findattr__("__file__") == null) { + // Should probably never happen (but maybe with an odd custom builtins, or + // Java Integration) + Py.writeDebug(IMPORT_LOG, String.format("Warning: %s __file__ is unknown", name)); + } + try { PyFrame f = new PyFrame(code, module.__dict__, module.__dict__, null); code.call(f); @@ -263,12 +268,6 @@ Py.getSystemState().modules.__delitem__(name.intern()); throw t; } - if(moduleLocation != null) { - module.__setattr__("__file__", - new PyString(moduleLocation)); - }else{ - Py.writeDebug(IMPORT_LOG, "No fileName known to set __file__ for " + name + "."); - } return module; } @@ -419,23 +418,25 @@ return load_module.__call__(new PyObject[] { new PyString(name) }); } - public static PyObject loadFromCompiled(String name, InputStream stream, - String filename) { - return createFromPyClass(name, stream, false, filename); + public static PyObject loadFromCompiled(String name, InputStream stream, String sourceName, + String compiledName) { + return createFromPyClass(name, stream, false, sourceName, compiledName); } static PyObject loadFromSource(PySystemState sys, String name, String modName, String entry) { - + String dirName = sys.getPath(entry); String sourceName = "__init__.py"; String compiledName = "__init__$py.class"; - String directoryName = sys.getPath(entry); - // displayDirName is for identification purposes (e.g. - // __file__): when null it forces java.io.File to be a - // relative path (e.g. foo/bar.py instead of /tmp/foo/bar.py) + // display names are for identification purposes (e.g. __file__): when entry is + // null it forces java.io.File to be a relative path (e.g. foo/bar.py instead of + // /tmp/foo/bar.py) String displayDirName = entry.equals("") ? null : entry.toString(); + String displaySourceName = new File(new File(displayDirName, name), sourceName).getPath(); + String displayCompiledName = new File(new File(displayDirName, name), + compiledName).getPath(); // First check for packages - File dir = new File(directoryName, name); + File dir = new File(dirName, name); File sourceFile = new File(dir, sourceName); File compiledFile = new File(dir, compiledName); @@ -445,48 +446,38 @@ Py.writeDebug(IMPORT_LOG, "trying source " + dir.getPath()); sourceName = name + ".py"; compiledName = name + "$py.class"; - sourceFile = new File(directoryName, sourceName); - compiledFile = new File(directoryName, compiledName); + displaySourceName = new File(displayDirName, sourceName).getPath(); + displayCompiledName = new File(displayDirName, compiledName).getPath(); + sourceFile = new File(dirName, sourceName); + compiledFile = new File(dirName, compiledName); } else { PyModule m = addModule(modName); PyObject filename = new PyString(new File(displayDirName, name).getPath()); - m.__dict__.__setitem__("__path__", new PyList( - new PyObject[] { filename })); - m.__dict__.__setitem__("__file__", filename); + m.__dict__.__setitem__("__path__", new PyList(new PyObject[] {filename})); } if (sourceFile.isFile() && caseok(sourceFile, sourceName)) { - String filename; - if (pkg) { - filename = new File(new File(displayDirName, name), sourceName).getPath(); - } else { - filename = new File(displayDirName, sourceName).getPath(); - } - if(compiledFile.isFile() && caseok(compiledFile, compiledName)) { - Py.writeDebug(IMPORT_LOG, "trying precompiled " - + compiledFile.getPath()); + if (compiledFile.isFile() && caseok(compiledFile, compiledName)) { + Py.writeDebug(IMPORT_LOG, "trying precompiled " + compiledFile.getPath()); long pyTime = sourceFile.lastModified(); long classTime = compiledFile.lastModified(); - if(classTime >= pyTime) { - // XXX: filename should use compiledName here (not - // sourceName), but this currently breaks source - // code printed out in tracebacks - PyObject ret = createFromPyClass(modName, makeStream(compiledFile), - true, filename); - if(ret != null) { + if (classTime >= pyTime) { + PyObject ret = createFromPyClass(modName, makeStream(compiledFile), true, + displaySourceName, displayCompiledName); + if (ret != null) { return ret; } } } - return createFromSource(modName, makeStream(sourceFile), filename, + return createFromSource(modName, makeStream(sourceFile), displaySourceName, compiledFile.getPath()); } + // If no source, try loading precompiled - Py.writeDebug(IMPORT_LOG, "trying precompiled with no source " - + compiledFile.getPath()); - if(compiledFile.isFile() && caseok(compiledFile, compiledName)) { - String filename = new File(displayDirName, compiledName).getPath(); - return createFromPyClass(modName, makeStream(compiledFile), true, filename); + Py.writeDebug(IMPORT_LOG, "trying precompiled with no source " + compiledFile.getPath()); + if (compiledFile.isFile() && caseok(compiledFile, compiledName)) { + return createFromPyClass(modName, makeStream(compiledFile), true, displaySourceName, + displayCompiledName); } return null; } Modified: trunk/jython/src/org/python/modules/imp.java =================================================================== --- trunk/jython/src/org/python/modules/imp.java 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/src/org/python/modules/imp.java 2008-11-22 23:23:48 UTC (rev 5601) @@ -186,13 +186,13 @@ if (o == Py.NoConversion) { throw Py.TypeError("must be a file-like object"); } + String compiledName; switch (type) { case PY_SOURCE: // XXX: This should load the accompanying byte // code file instead, if it exists String resolvedFilename = sys.getPath(filename.toString()); - String compiledName = - org.python.core.imp.makeCompiledFilename(resolvedFilename); + compiledName = org.python.core.imp.makeCompiledFilename(resolvedFilename); if (name.endsWith(".__init__")) { name = name.substring(0, name.length() - ".__init__".length()); } else if (name.equals("__init__")) { @@ -204,8 +204,15 @@ compiledName); break; case PY_COMPILED: + compiledName = filename.toString(); + // XXX: Ideally we wouldn't care about sourceName here (see + // http://bugs.jython.org/issue1605847 msg3805) + String sourceName = compiledName; + if (compiledName.endsWith("$py.class")) { + sourceName = compiledName.substring(0, compiledName.length() - 9) + ".py"; + } mod = org.python.core.imp.loadFromCompiled( - name.intern(), (InputStream)o, filename.toString()); + name.intern(), (InputStream)o, sourceName, filename.toString()); break; case PKG_DIRECTORY: PyModule m = org.python.core.imp.addModule(name); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-22 22:37:55
|
Revision: 5600 http://jython.svn.sourceforge.net/jython/?rev=5600&view=rev Author: pjenvey Date: 2008-11-22 22:37:49 +0000 (Sat, 22 Nov 2008) Log Message: ----------- from: http://svn.python.org/projects/python/branches/release25-maint/Lib/warnings.py@47273 Added Paths: ----------- trunk/jython/Lib/warnings.py Added: trunk/jython/Lib/warnings.py =================================================================== --- trunk/jython/Lib/warnings.py (rev 0) +++ trunk/jython/Lib/warnings.py 2008-11-22 22:37:49 UTC (rev 5600) @@ -0,0 +1,264 @@ +"""Python part of the warnings subsystem.""" + +# Note: function level imports should *not* be used +# in this module as it may cause import lock deadlock. +# See bug 683658. +import sys, types +import linecache + +__all__ = ["warn", "showwarning", "formatwarning", "filterwarnings", + "resetwarnings"] + +# filters contains a sequence of filter 5-tuples +# The components of the 5-tuple are: +# - an action: error, ignore, always, default, module, or once +# - a compiled regex that must match the warning message +# - a class representing the warning category +# - a compiled regex that must match the module that is being warned +# - a line number for the line being warning, or 0 to mean any line +# If either if the compiled regexs are None, match anything. +filters = [] +defaultaction = "default" +onceregistry = {} + +def warn(message, category=None, stacklevel=1): + """Issue a warning, or maybe ignore it or raise an exception.""" + # Check if message is already a Warning object + if isinstance(message, Warning): + category = message.__class__ + # Check category argument + if category is None: + category = UserWarning + assert issubclass(category, Warning) + # Get context information + try: + caller = sys._getframe(stacklevel) + except ValueError: + globals = sys.__dict__ + lineno = 1 + else: + globals = caller.f_globals + lineno = caller.f_lineno + if '__name__' in globals: + module = globals['__name__'] + else: + module = "<string>" + filename = globals.get('__file__') + if filename: + fnl = filename.lower() + if fnl.endswith((".pyc", ".pyo")): + filename = filename[:-1] + else: + if module == "__main__": + try: + filename = sys.argv[0] + except AttributeError: + # embedded interpreters don't have sys.argv, see bug #839151 + filename = '__main__' + if not filename: + filename = module + registry = globals.setdefault("__warningregistry__", {}) + warn_explicit(message, category, filename, lineno, module, registry, + globals) + +def warn_explicit(message, category, filename, lineno, + module=None, registry=None, module_globals=None): + if module is None: + module = filename or "<unknown>" + if module[-3:].lower() == ".py": + module = module[:-3] # XXX What about leading pathname? + if registry is None: + registry = {} + if isinstance(message, Warning): + text = str(message) + category = message.__class__ + else: + text = message + message = category(message) + key = (text, category, lineno) + # Quick test for common case + if registry.get(key): + return + # Search the filters + for item in filters: + action, msg, cat, mod, ln = item + if ((msg is None or msg.match(text)) and + issubclass(category, cat) and + (mod is None or mod.match(module)) and + (ln == 0 or lineno == ln)): + break + else: + action = defaultaction + # Early exit actions + if action == "ignore": + registry[key] = 1 + return + + # Prime the linecache for formatting, in case the + # "file" is actually in a zipfile or something. + linecache.getlines(filename, module_globals) + + if action == "error": + raise message + # Other actions + if action == "once": + registry[key] = 1 + oncekey = (text, category) + if onceregistry.get(oncekey): + return + onceregistry[oncekey] = 1 + elif action == "always": + pass + elif action == "module": + registry[key] = 1 + altkey = (text, category, 0) + if registry.get(altkey): + return + registry[altkey] = 1 + elif action == "default": + registry[key] = 1 + else: + # Unrecognized actions are errors + raise RuntimeError( + "Unrecognized action (%r) in warnings.filters:\n %s" % + (action, item)) + # Print message and context + showwarning(message, category, filename, lineno) + +def showwarning(message, category, filename, lineno, file=None): + """Hook to write a warning to a file; replace if you like.""" + if file is None: + file = sys.stderr + try: + file.write(formatwarning(message, category, filename, lineno)) + except IOError: + pass # the file (probably stderr) is invalid - this warning gets lost. + +def formatwarning(message, category, filename, lineno): + """Function to format a warning the standard way.""" + s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) + line = linecache.getline(filename, lineno).strip() + if line: + s = s + " " + line + "\n" + return s + +def filterwarnings(action, message="", category=Warning, module="", lineno=0, + append=0): + """Insert an entry into the list of warnings filters (at the front). + + Use assertions to check that all arguments have the right type.""" + import re + assert action in ("error", "ignore", "always", "default", "module", + "once"), "invalid action: %r" % (action,) + assert isinstance(message, basestring), "message must be a string" + assert isinstance(category, (type, types.ClassType)), \ + "category must be a class" + assert issubclass(category, Warning), "category must be a Warning subclass" + assert isinstance(module, basestring), "module must be a string" + assert isinstance(lineno, int) and lineno >= 0, \ + "lineno must be an int >= 0" + item = (action, re.compile(message, re.I), category, + re.compile(module), lineno) + if append: + filters.append(item) + else: + filters.insert(0, item) + +def simplefilter(action, category=Warning, lineno=0, append=0): + """Insert a simple entry into the list of warnings filters (at the front). + + A simple filter matches all modules and messages. + """ + assert action in ("error", "ignore", "always", "default", "module", + "once"), "invalid action: %r" % (action,) + assert isinstance(lineno, int) and lineno >= 0, \ + "lineno must be an int >= 0" + item = (action, None, category, None, lineno) + if append: + filters.append(item) + else: + filters.insert(0, item) + +def resetwarnings(): + """Clear the list of warning filters, so that no filters are active.""" + filters[:] = [] + +class _OptionError(Exception): + """Exception used by option processing helpers.""" + pass + +# Helper to process -W options passed via sys.warnoptions +def _processoptions(args): + for arg in args: + try: + _setoption(arg) + except _OptionError, msg: + print >>sys.stderr, "Invalid -W option ignored:", msg + +# Helper for _processoptions() +def _setoption(arg): + import re + parts = arg.split(':') + if len(parts) > 5: + raise _OptionError("too many fields (max 5): %r" % (arg,)) + while len(parts) < 5: + parts.append('') + action, message, category, module, lineno = [s.strip() + for s in parts] + action = _getaction(action) + message = re.escape(message) + category = _getcategory(category) + module = re.escape(module) + if module: + module = module + '$' + if lineno: + try: + lineno = int(lineno) + if lineno < 0: + raise ValueError + except (ValueError, OverflowError): + raise _OptionError("invalid lineno %r" % (lineno,)) + else: + lineno = 0 + filterwarnings(action, message, category, module, lineno) + +# Helper for _setoption() +def _getaction(action): + if not action: + return "default" + if action == "all": return "always" # Alias + for a in ('default', 'always', 'ignore', 'module', 'once', 'error'): + if a.startswith(action): + return a + raise _OptionError("invalid action: %r" % (action,)) + +# Helper for _setoption() +def _getcategory(category): + import re + if not category: + return Warning + if re.match("^[a-zA-Z0-9_]+$", category): + try: + cat = eval(category) + except NameError: + raise _OptionError("unknown warning category: %r" % (category,)) + else: + i = category.rfind(".") + module = category[:i] + klass = category[i+1:] + try: + m = __import__(module, None, None, [klass]) + except ImportError: + raise _OptionError("invalid module name: %r" % (module,)) + try: + cat = getattr(m, klass) + except AttributeError: + raise _OptionError("unknown warning category: %r" % (category,)) + if not issubclass(cat, Warning): + raise _OptionError("invalid warning category: %r" % (category,)) + return cat + +# Module initialization +_processoptions(sys.warnoptions) +simplefilter("ignore", category=PendingDeprecationWarning, append=1) +simplefilter("ignore", category=ImportWarning, append=1) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-11-22 20:39:56
|
Revision: 5599 http://jython.svn.sourceforge.net/jython/?rev=5599&view=rev Author: fwierzbicki Date: 2008-11-22 20:39:54 +0000 (Sat, 22 Nov 2008) Log Message: ----------- Removed XXX -- looking at the code some more makes me comfortable with passing "flags" on. Modified Paths: -------------- trunk/jython/src/org/python/core/Py.java Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2008-11-22 19:18:53 UTC (rev 5598) +++ trunk/jython/src/org/python/core/Py.java 2008-11-22 20:39:54 UTC (rev 5599) @@ -1675,7 +1675,6 @@ if (frame != null && frame.f_code != null) { cflags = new CompilerFlags(frame.f_code.co_flags | flags); } else { - //XXX: should this really pass flags or not? cflags = new CompilerFlags(flags); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |