From: <fwi...@us...> - 2009-08-16 02:49:33
|
Revision: 6671 http://jython.svn.sourceforge.net/jython/?rev=6671&view=rev Author: fwierzbicki Date: 2009-08-16 02:49:27 +0000 (Sun, 16 Aug 2009) Log Message: ----------- Better match with CPython for col_offset on BoolOp with left arg in parens. Modified Paths: -------------- trunk/jython/grammar/Python.g trunk/jython/src/org/python/antlr/GrammarActions.java Modified: trunk/jython/grammar/Python.g =================================================================== --- trunk/jython/grammar/Python.g 2009-08-16 02:36:35 UTC (rev 6670) +++ trunk/jython/grammar/Python.g 2009-08-16 02:49:27 UTC (rev 6671) @@ -1038,10 +1038,15 @@ ; //or_test: and_test ('or' and_test)* -or_test[expr_contextType ctype] +or_test + [expr_contextType ctype] returns [Token leftTok] @after { if ($or != null) { - $or_test.tree = actions.makeBoolOp($left.tree, boolopType.Or, $right); + Token tok = $left.start; + if ($left.leftTok != null) { + tok = $left.leftTok; + } + $or_test.tree = actions.makeBoolOp(tok, $left.tree, boolopType.Or, $right); } } : left=and_test[ctype] @@ -1053,10 +1058,15 @@ ; //and_test: not_test ('and' not_test)* -and_test[expr_contextType ctype] +and_test + [expr_contextType ctype] returns [Token leftTok] @after { if ($and != null) { - $and_test.tree = actions.makeBoolOp($left.tree, boolopType.And, $right); + Token tok = $left.start; + if ($left.leftTok != null) { + tok = $left.leftTok; + } + $and_test.tree = actions.makeBoolOp(tok, $left.tree, boolopType.And, $right); } } : left=not_test[ctype] @@ -1068,18 +1078,21 @@ ; //not_test: 'not' not_test | comparison -not_test[expr_contextType ctype] - : NOT nt=not_test[ctype] +not_test + [expr_contextType ctype] returns [Token leftTok] + : NOT nt=not_test[ctype] {$leftTok = $nt.leftTok;} -> ^(NOT<UnaryOp>[$NOT, unaryopType.Not, actions.castExpr($nt.tree)]) - | comparison[ctype] + | comparison[ctype] {$leftTok = $comparison.leftTok;} ; //comparison: expr (comp_op expr)* -comparison[expr_contextType ctype] +comparison + [expr_contextType ctype] returns [Token leftTok] @init { List cmps = new ArrayList(); } @after { + $leftTok = $left.leftTok; if (!cmps.isEmpty()) { $comparison.tree = new Compare($left.start, actions.castExpr($left.tree), actions.makeCmpOps(cmps), actions.castExprs($right)); @@ -1125,14 +1138,18 @@ //expr: xor_expr ('|' xor_expr)* -expr[expr_contextType ect] +expr + [expr_contextType ect] returns [Token leftTok] scope { expr_contextType ctype; + Token lparen; } @init { $expr::ctype = ect; + $expr::lparen = null; } @after { + $leftTok = $expr::lparen; if ($op != null) { $expr.tree = actions.makeBinOp($left.tree, operatorType.BitOr, $right); } @@ -1342,7 +1359,7 @@ // '`' testlist1 '`' | // NAME | NUMBER | STRING+) atom - : LPAREN + : LPAREN {$expr::lparen = $LPAREN;} ( yield_expr -> yield_expr | testlist_gexp Modified: trunk/jython/src/org/python/antlr/GrammarActions.java =================================================================== --- trunk/jython/src/org/python/antlr/GrammarActions.java 2009-08-16 02:36:35 UTC (rev 6670) +++ trunk/jython/src/org/python/antlr/GrammarActions.java 2009-08-16 02:49:27 UTC (rev 6671) @@ -642,11 +642,11 @@ return result; } - BoolOp makeBoolOp(PythonTree left, boolopType op, List right) { + BoolOp makeBoolOp(Token t, PythonTree left, boolopType op, List right) { List values = new ArrayList(); values.add(left); values.addAll(right); - return new BoolOp(left, op, castExprs(values)); + return new BoolOp(t, op, castExprs(values)); } BinOp makeBinOp(PythonTree left, operatorType op, List rights) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2009-08-16 10:28:57
|
Revision: 6676 http://jython.svn.sourceforge.net/jython/?rev=6676&view=rev Author: cgroves Date: 2009-08-16 10:28:49 +0000 (Sun, 16 Aug 2009) Log Message: ----------- Continue looking for methods to merge up the inheritance chain if the non-public class being merged has a parent that's non-public as well. Fixes issue 1430. Modified Paths: -------------- trunk/jython/Lib/test/test_java_visibility.py trunk/jython/src/org/python/core/PyJavaType.java Added Paths: ----------- trunk/jython/tests/java/org/python/tests/multihidden/ trunk/jython/tests/java/org/python/tests/multihidden/BaseConnection.java trunk/jython/tests/java/org/python/tests/multihidden/SpecialConnection.java Modified: trunk/jython/Lib/test/test_java_visibility.py =================================================================== --- trunk/jython/Lib/test/test_java_visibility.py 2009-08-16 08:11:44 UTC (rev 6675) +++ trunk/jython/Lib/test/test_java_visibility.py 2009-08-16 10:28:49 UTC (rev 6676) @@ -10,6 +10,7 @@ from org.python.tests import VisibilityResults as Results from org.python.tests.RedundantInterfaceDeclarations import (Implementation, ExtraClass, ExtraString, ExtraStringAndClass, ExtraClassAndString) +from org.python.tests.multihidden import BaseConnection class VisibilityTest(unittest.TestCase): def test_invisible(self): @@ -167,6 +168,15 @@ self.assertEquals("int", instance.call(7)) self.assertEquals("Class", instance.call(LinkedList)) + def test_extending_multiple_hidden_classes(self): + '''Tests multiple levels of non-public classes overriding public methods from superclasses + + Bug #1430''' + conn = BaseConnection.newConnection() + self.assertEquals("wrapper close", conn.close()) + self.assertEquals("special close", conn.close(7)) + + class JavaClassTest(unittest.TestCase): def test_class_methods_visible(self): self.assertFalse(HashMap.isInterface(), Modified: trunk/jython/src/org/python/core/PyJavaType.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaType.java 2009-08-16 08:11:44 UTC (rev 6675) +++ trunk/jython/src/org/python/core/PyJavaType.java 2009-08-16 10:28:49 UTC (rev 6676) @@ -592,6 +592,11 @@ } if (forClass.getSuperclass() != null) { mergeMethods(forClass.getSuperclass()); + if (!Modifier.isPublic(forClass.getSuperclass().getModifiers())) { + // If the superclass is also not public, it needs to get the same treatment as we + // can't call its methods either. + handleSuperMethodArgCollisions(forClass.getSuperclass()); + } } } Added: trunk/jython/tests/java/org/python/tests/multihidden/BaseConnection.java =================================================================== --- trunk/jython/tests/java/org/python/tests/multihidden/BaseConnection.java (rev 0) +++ trunk/jython/tests/java/org/python/tests/multihidden/BaseConnection.java 2009-08-16 10:28:49 UTC (rev 6676) @@ -0,0 +1,33 @@ +package org.python.tests.multihidden; + +/** + * Derived from the Oracle JDBC connection classes for use in test_extending_multiple_hidden_classes + * in test_java_visibility. + */ +public class BaseConnection { + public static Connection newConnection() { + return new Connection(); + } + + public String close() { + return "base close"; + } +} + +class Connection extends ConnectionWrapper implements SpecialConnection { + + public String close(int foo) { + return "special close"; + } +} + +class ConnectionWrapper extends BaseConnection { + +// This method, plus the fact that Connection implements an interface with a different +// close, causes BaseConnection.close to be hidden in Connection because +// ConnectionWrapper is not public + @Override + public String close() { + return "wrapper close"; + } +} Added: trunk/jython/tests/java/org/python/tests/multihidden/SpecialConnection.java =================================================================== --- trunk/jython/tests/java/org/python/tests/multihidden/SpecialConnection.java (rev 0) +++ trunk/jython/tests/java/org/python/tests/multihidden/SpecialConnection.java 2009-08-16 10:28:49 UTC (rev 6676) @@ -0,0 +1,5 @@ +package org.python.tests.multihidden; + +public interface SpecialConnection { + String close(int foo); +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2009-08-16 22:26:14
|
Revision: 6682 http://jython.svn.sourceforge.net/jython/?rev=6682&view=rev Author: cgroves Date: 2009-08-16 22:25:58 +0000 (Sun, 16 Aug 2009) Log Message: ----------- Remove the ant exposer from Eclipse as it never seemed to work. Modified Paths: -------------- trunk/jython/.classpath trunk/jython/.project Removed Paths: ------------- trunk/jython/.externalToolBuilders/ Modified: trunk/jython/.classpath =================================================================== --- trunk/jython/.classpath 2009-08-16 18:21:50 UTC (rev 6681) +++ trunk/jython/.classpath 2009-08-16 22:25:58 UTC (rev 6682) @@ -1,10 +1,9 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> - <classpathentry excluding="com/ziclix/python/sql/handler/InformixDataHandler.java|com/ziclix/python/sql/handler/OracleDataHandler.java" kind="src" output="build/classes" path="src"/> + <classpathentry excluding="com/ziclix/python/sql/handler/InformixDataHandler.java|com/ziclix/python/sql/handler/OracleDataHandler.java" kind="src" path="src"/> <classpathentry kind="src" path="tests/modjy/java"/> - <classpathentry kind="src" output="build/classes" path="build/gensrc"/> - <classpathentry kind="src" output="build/classes" path="tests/java"/> - <classpathentry kind="src" path="bugtests/classes"/> + <classpathentry kind="src" path="build/gensrc"/> + <classpathentry kind="src" path="tests/java"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/3"/> <classpathentry kind="lib" path="extlibs/jline-0.9.95-SNAPSHOT.jar"/> @@ -20,7 +19,7 @@ <classpathentry kind="lib" path="extlibs/constantine-0.4.jar"/> <classpathentry kind="lib" path="extlibs/jna-posix.jar"/> <classpathentry kind="lib" path="extlibs/mockrunner-0.4.1/jar/jdom.jar"/> - <classpathentry kind="lib" path="extlibs/mockrunner-0.4.1/lib/jdk1.5/j2ee1.3/mockrunner-servlet.jar"/> - <classpathentry kind="lib" path="extlibs/jna.jar"/> - <classpathentry kind="output" path="bugtests/classes"/> + <classpathentry kind="lib" path="extlibs/mockrunner-0.4.1/lib/jdk1.5/j2ee1.3/mockrunner-servlet.jar"/> + <classpathentry kind="lib" path="extlibs/jna.jar"/> + <classpathentry kind="output" path="build/classes"/> </classpath> Modified: trunk/jython/.project =================================================================== --- trunk/jython/.project 2009-08-16 18:21:50 UTC (rev 6681) +++ trunk/jython/.project 2009-08-16 22:25:58 UTC (rev 6682) @@ -10,16 +10,6 @@ <arguments> </arguments> </buildCommand> - <buildCommand> - <name>org.eclipse.ui.externaltools.ExternalToolBuilder</name> - <triggers>auto,</triggers> - <arguments> - <dictionary> - <key>LaunchConfigHandle</key> - <value><project>/.externalToolBuilders/Expose and jar.launch</value> - </dictionary> - </arguments> - </buildCommand> </buildSpec> <natures> <nature>org.eclipse.jdt.core.javanature</nature> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-08-17 03:15:37
|
Revision: 6690 http://jython.svn.sourceforge.net/jython/?rev=6690&view=rev Author: fwierzbicki Date: 2009-08-17 03:15:31 +0000 (Mon, 17 Aug 2009) Log Message: ----------- Better match of CPython col_offset for factors with parens like: (a - b) * c Modified Paths: -------------- trunk/jython/Lib/test/test_ast.py trunk/jython/grammar/Python.g trunk/jython/src/org/python/antlr/GrammarActions.java Modified: trunk/jython/Lib/test/test_ast.py =================================================================== --- trunk/jython/Lib/test/test_ast.py 2009-08-17 02:30:53 UTC (rev 6689) +++ trunk/jython/Lib/test/test_ast.py 2009-08-17 03:15:31 UTC (rev 6690) @@ -67,11 +67,12 @@ # Parens and BoolOp "(a == '') and b", "not (a == '') or b", + # Parens and BinOp + "(a - b) * c", # for statements with naked tuples "for a,b in c: pass", "[(a,b) for a,b in c]", "((a,b) for a,b in c)", - ] # These are compiled through "single" @@ -336,6 +337,7 @@ ('Module', [('Continue', (1, 0))]), ('Module', [('Expr', (1, 0), ('BoolOp', (1, 0), ('And',), [('Compare', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('Eq',)], [('Str', (1, 6), '')]), ('Name', (1, 14), 'b', ('Load',))]))]), ('Module', [('Expr', (1, 0), ('BoolOp', (1, 0), ('Or',), [('UnaryOp', (1, 0), ('Not',), ('Compare', (1, 5), ('Name', (1, 5), 'a', ('Load',)), [('Eq',)], [('Str', (1, 10), '')])), ('Name', (1, 17), 'b', ('Load',))]))]), +('Module', [('Expr', (1, 0), ('BinOp', (1, 0), ('BinOp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), ('Sub',), ('Name', (1, 5), 'b', ('Load',))), ('Mult',), ('Name', (1, 10), 'c', ('Load',))))]), ('Module', [('For', (1, 0), ('Tuple', (1, 4), [('Name', (1, 4), 'a', ('Store',)), ('Name', (1, 6), 'b', ('Store',))], ('Store',)), ('Name', (1, 11), 'c', ('Load',)), [('Pass', (1, 14))], [])]), ('Module', [('Expr', (1, 0), ('ListComp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [])]))]), ('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [])]))]), Modified: trunk/jython/grammar/Python.g =================================================================== --- trunk/jython/grammar/Python.g 2009-08-17 02:30:53 UTC (rev 6689) +++ trunk/jython/grammar/Python.g 2009-08-17 03:15:31 UTC (rev 6690) @@ -1204,7 +1204,7 @@ } @after { if (!ops.isEmpty()) { - $shift_expr.tree = actions.makeBinOp($left.tree, ops, $right, toks); + $shift_expr.tree = actions.makeBinOp($left.start, $left.tree, ops, $right, toks); } $lparen = $left.lparen; } @@ -1237,7 +1237,7 @@ } @after { if (!ops.isEmpty()) { - $arith_expr.tree = actions.makeBinOp($left.tree, ops, $right, toks); + $arith_expr.tree = actions.makeBinOp($left.start, $left.tree, ops, $right, toks); } $lparen = $left.lparen; } @@ -1279,7 +1279,11 @@ @after { $lparen = $left.lparen; if (!ops.isEmpty()) { - $term.tree = actions.makeBinOp($left.tree, ops, $right, toks); + Token tok = $left.start; + if ($left.lparen != null) { + tok = $left.lparen; + } + $term.tree = actions.makeBinOp(tok, $left.tree, ops, $right, toks); } } : left=factor Modified: trunk/jython/src/org/python/antlr/GrammarActions.java =================================================================== --- trunk/jython/src/org/python/antlr/GrammarActions.java 2009-08-17 02:30:53 UTC (rev 6689) +++ trunk/jython/src/org/python/antlr/GrammarActions.java 2009-08-17 03:15:31 UTC (rev 6690) @@ -658,8 +658,8 @@ return current; } - BinOp makeBinOp(PythonTree left, List ops, List rights, List toks) { - BinOp current = new BinOp(left, castExpr(left), (operatorType)ops.get(0), castExpr(rights.get(0))); + BinOp makeBinOp(Token t, PythonTree left, List ops, List rights, List toks) { + BinOp current = new BinOp(t, castExpr(left), (operatorType)ops.get(0), castExpr(rights.get(0))); for (int i = 1; i< rights.size(); i++) { expr right = castExpr(rights.get(i)); operatorType op = (operatorType)ops.get(i); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-08-17 13:26:06
|
Revision: 6691 http://jython.svn.sourceforge.net/jython/?rev=6691&view=rev Author: fwierzbicki Date: 2009-08-17 13:25:59 +0000 (Mon, 17 Aug 2009) Log Message: ----------- Better BinOp col_offsets. Modified Paths: -------------- trunk/jython/grammar/Python.g trunk/jython/src/org/python/antlr/GrammarActions.java Modified: trunk/jython/grammar/Python.g =================================================================== --- trunk/jython/grammar/Python.g 2009-08-17 03:15:31 UTC (rev 6690) +++ trunk/jython/grammar/Python.g 2009-08-17 13:25:59 UTC (rev 6691) @@ -1149,7 +1149,11 @@ @after { $leftTok = $left.lparen; if ($op != null) { - $expr.tree = actions.makeBinOp($left.tree, operatorType.BitOr, $right); + Token tok = $left.start; + if ($left.lparen != null) { + tok = $left.lparen; + } + $expr.tree = actions.makeBinOp(tok, $left.tree, operatorType.BitOr, $right); } } : left=xor_expr @@ -1166,7 +1170,11 @@ returns [Token lparen = null] @after { if ($op != null) { - $xor_expr.tree = actions.makeBinOp($left.tree, operatorType.BitXor, $right); + Token tok = $left.start; + if ($left.lparen != null) { + tok = $left.lparen; + } + $xor_expr.tree = actions.makeBinOp(tok, $left.tree, operatorType.BitXor, $right); } $lparen = $left.lparen; } @@ -1183,7 +1191,11 @@ returns [Token lparen = null] @after { if ($op != null) { - $and_expr.tree = actions.makeBinOp($left.tree, operatorType.BitAnd, $right); + Token tok = $left.start; + if ($left.lparen != null) { + tok = $left.lparen; + } + $and_expr.tree = actions.makeBinOp(tok, $left.tree, operatorType.BitAnd, $right); } $lparen = $left.lparen; } @@ -1204,7 +1216,11 @@ } @after { if (!ops.isEmpty()) { - $shift_expr.tree = actions.makeBinOp($left.start, $left.tree, ops, $right, toks); + Token tok = $left.start; + if ($left.lparen != null) { + tok = $left.lparen; + } + $shift_expr.tree = actions.makeBinOp(tok, $left.tree, ops, $right, toks); } $lparen = $left.lparen; } @@ -1237,7 +1253,11 @@ } @after { if (!ops.isEmpty()) { - $arith_expr.tree = actions.makeBinOp($left.start, $left.tree, ops, $right, toks); + Token tok = $left.start; + if ($left.lparen != null) { + tok = $left.lparen; + } + $arith_expr.tree = actions.makeBinOp(tok, $left.tree, ops, $right, toks); } $lparen = $left.lparen; } @@ -1364,7 +1384,7 @@ if ($d != null) { List right = new ArrayList(); right.add($factor.tree); - $etype = actions.makeBinOp($etype, operatorType.Pow, right); + $etype = actions.makeBinOp($atom.start, $etype, operatorType.Pow, right); } } ; Modified: trunk/jython/src/org/python/antlr/GrammarActions.java =================================================================== --- trunk/jython/src/org/python/antlr/GrammarActions.java 2009-08-17 03:15:31 UTC (rev 6690) +++ trunk/jython/src/org/python/antlr/GrammarActions.java 2009-08-17 13:25:59 UTC (rev 6691) @@ -649,8 +649,8 @@ return new BoolOp(t, op, castExprs(values)); } - BinOp makeBinOp(PythonTree left, operatorType op, List rights) { - BinOp current = new BinOp(left, castExpr(left), op, castExpr(rights.get(0))); + BinOp makeBinOp(Token t, PythonTree left, operatorType op, List rights) { + BinOp current = new BinOp(t, castExpr(left), op, castExpr(rights.get(0))); for (int i = 1; i< rights.size(); i++) { expr right = castExpr(rights.get(i)); current = new BinOp(left, current, op, right); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2009-08-23 19:48:03
|
Revision: 6713 http://jython.svn.sourceforge.net/jython/?rev=6713&view=rev Author: cgroves Date: 2009-08-23 19:47:55 +0000 (Sun, 23 Aug 2009) Log Message: ----------- Roll back 6532-6534 and 6548 to keep __javaname__ and sys.javaproxy_dir from going out with 2.5.1. __javaname__ just went away in favor of a naming proxymaker on the customizable-proxymaker branch, and sys.javaproxy_dir doesn't make sense without named proxies. I'll need to re-commit 6533, 6534 and 6548 when I merge customizable-proxymaker to trunk. Modified Paths: -------------- trunk/jython/Lib/test/test_java_subclasses.py trunk/jython/NEWS trunk/jython/src/org/python/compiler/Module.java trunk/jython/src/org/python/core/MakeProxies.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyJavaType.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/core/util/StringUtil.java trunk/jython/src/org/python/expose/generate/ExposeTask.java trunk/jython/src/org/python/util/GlobMatchingTask.java trunk/jython/src/org/python/util/JycompileAntTask.java Removed Paths: ------------- trunk/jython/Lib/test/import_as_java_class.py trunk/jython/Lib/test/static_proxy.py trunk/jython/src/org/python/util/CompileProxiesTask.java trunk/jython/src/org/python/util/FileNameMatchingTask.java Deleted: trunk/jython/Lib/test/import_as_java_class.py =================================================================== --- trunk/jython/Lib/test/import_as_java_class.py 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/Lib/test/import_as_java_class.py 2009-08-23 19:47:55 UTC (rev 6713) @@ -1,7 +0,0 @@ -# Part of test_java_subclasses.StaticProxyCompilationTest -from java.lang import Class - -# Grab the proxy class statically compiled by the containing test -cls = Class.forName("test.static_proxy.RunnableImpl") -# Instantiating the proxy class should import the module containing it and create the Python side -assert cls.newInstance().meth() == 78 Deleted: trunk/jython/Lib/test/static_proxy.py =================================================================== --- trunk/jython/Lib/test/static_proxy.py 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/Lib/test/static_proxy.py 2009-08-23 19:47:55 UTC (rev 6713) @@ -1,11 +0,0 @@ -# Part of test_java_subclasses.StaticProxyCompilationTest. This needs to be its own module -# so the statically compiled proxy can import it. -from java.lang import Runnable - -class RunnableImpl(Runnable): - __javaname__ = "test.static_proxy.RunnableImpl" - def run(self): - pass - - def meth(self): - return 78 Modified: trunk/jython/Lib/test/test_java_subclasses.py =================================================================== --- trunk/jython/Lib/test/test_java_subclasses.py 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/Lib/test/test_java_subclasses.py 2009-08-23 19:47:55 UTC (rev 6713) @@ -1,8 +1,6 @@ '''Tests subclassing Java classes in Python''' import os import sys -import tempfile -import subprocess import unittest from test import test_support @@ -323,56 +321,10 @@ self.assertEquals(len(called), 1) -class SettingJavaClassNameTest(unittest.TestCase): - def test_setting_name(self): - class Fixedname(Runnable): - __javaname__ = 'name.set.in.Python' - def run(self): - pass - self.assertEquals('name.set.in.Python', Fixedname().getClass().name) - try: - class NumberPackageName(Runnable): - __javaname__ = 'ok.7.ok' - def run(self): - pass - self.fail("Shouldn't be able to set a package name that starts with a digit") - except TypeError: - pass - try: - class LiteralPackageName(Runnable): - __javaname__ = 'ok.true.ok' - def run(self): - pass - self.fail("Shouldn't be able to use a Java literal as a package name") - except TypeError: - pass - -class StaticProxyCompilationTest(unittest.TestCase): - def setUp(self): - self.orig_proxy_dir = sys.javaproxy_dir - sys.javaproxy_dir = tempfile.mkdtemp() - - def tearDown(self): - sys.javaproxy_dir = self.orig_proxy_dir - - def test_proxies_without_classloader(self): - # importing with proxy_dir set compiles RunnableImpl there - import static_proxy - - # Use the existing environment with the proxy dir added on the classpath - env = dict(os.environ) - env["CLASSPATH"] = sys.javaproxy_dir - script = test_support.findfile("import_as_java_class.py") - self.assertEquals(subprocess.call([sys.executable, "-J-Dpython.cachedir.skip=true", - script], env=env), - 0) - def test_main(): test_support.run_unittest(InterfaceTest, TableModelTest, AutoSuperTest, PythonSubclassesTest, AbstractOnSyspathTest, - ContextClassloaderTest, - SettingJavaClassNameTest, - StaticProxyCompilationTest) + ContextClassloaderTest) Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/NEWS 2009-08-23 19:47:55 UTC (rev 6713) @@ -4,8 +4,6 @@ New Features - Upgraded to ANTLR 3.1.3 - [ 1859477 ] Dynamically loaded ServletFilters like PyServlet - - Setting __javaname__ in classes subclassing Java classes or implementing Java interfaces sets - the name of the produced proxy class. - Built in JSR 223 scripting engine, with LiveTribe JSR 223 implementation for JDK 5 - Jython "-J-classpath cp_args_here" now works as expected for unix shell. Bugs Fixed Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/src/org/python/compiler/Module.java 2009-08-23 19:47:55 UTC (rev 6713) @@ -12,11 +12,6 @@ import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; -import org.python.antlr.ParseException; -import org.python.antlr.PythonTree; -import org.python.antlr.ast.Suite; -import org.python.antlr.base.mod; import org.python.core.CodeBootstrap; import org.python.core.CodeFlag; import org.python.core.CodeLoader; @@ -24,7 +19,11 @@ import org.python.core.Py; import org.python.core.PyException; import org.python.core.PyRunnableBootstrap; -import org.python.core.util.StringUtil; +import org.objectweb.asm.Type; +import org.python.antlr.ParseException; +import org.python.antlr.PythonTree; +import org.python.antlr.ast.Suite; +import org.python.antlr.base.mod; class PyIntegerConstant extends Constant implements ClassConstants, Opcodes { @@ -366,7 +365,20 @@ } List<PyCodeConstant> codes; + private boolean isJavaIdentifier(String s) { + char[] chars = s.toCharArray(); + if (chars.length == 0) + return false; + if (!Character.isJavaIdentifierStart(chars[0])) + return false; + for(int i=1; i<chars.length; i++) { + if (!Character.isJavaIdentifierPart(chars[i])) + return false; + } + return true; + } + //XXX: this can probably go away now that we can probably just copy the list. private List<String> toNameAr(List<String> names,boolean nullok) { int sz = names.size(); @@ -411,7 +423,7 @@ code.id = codes.size(); //Better names in the future? - if (StringUtil.isJavaIdentifier(name)) + if (isJavaIdentifier(name)) code.fname = name+"$"+code.id; else code.fname = "f$"+code.id; @@ -537,7 +549,7 @@ c.invokestatic("org/python/core/Py", "runMain", "(" + bootstrap + $strArr + ")V"); c.return_(); } - + public void addBootstrap() throws IOException { Code c = classfile.addMethod(CodeLoader.GET_BOOTSTRAP_METHOD_NAME, "()" + Type.getDescriptor(CodeBootstrap.class), @@ -643,7 +655,7 @@ String name, String filename, boolean linenumbers, boolean printResults, CompilerFlags cflags) - throws Exception + throws Exception { compile(node, ostream, name, filename, linenumbers, printResults, cflags, org.python.core.imp.NO_MTIME); } Modified: trunk/jython/src/org/python/core/MakeProxies.java =================================================================== --- trunk/jython/src/org/python/core/MakeProxies.java 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/src/org/python/core/MakeProxies.java 2009-08-23 19:47:55 UTC (rev 6713) @@ -8,7 +8,6 @@ import org.python.compiler.AdapterMaker; import org.python.compiler.JavaMaker; -import org.python.core.util.StringUtil; class MakeProxies { @@ -52,28 +51,13 @@ List<Class<?>> vinterfaces, String className, String proxyName, PyObject dict) { Class<?>[] interfaces = vinterfaces.toArray(new Class<?>[vinterfaces.size()]); - String fullProxyName; - PyObject customProxyName = dict.__finditem__("__javaname__"); - if (customProxyName != null) { - fullProxyName = Py.tojava(customProxyName, String.class); - if (!StringUtil.isJavaClassName(fullProxyName)) { - throw Py.TypeError(fullProxyName + " isn't a valid Java class name. Classes " + - "must be valid Java identifiers: " + - "http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#40625"); - } - Class<?> proxy = Py.findClass(fullProxyName); - if (proxy != null) { - return proxy; - } - } else { - fullProxyName = proxyPrefix + proxyName + "$" + proxyNumber++; - } + String fullProxyName = proxyPrefix + proxyName + "$" + proxyNumber++; String pythonModuleName; PyObject mn = dict.__finditem__("__module__"); if (mn == null) { pythonModuleName = "foo"; } else { - pythonModuleName = Py.tojava(mn, String.class); + pythonModuleName = (String) mn.__tojava__(String.class); } JavaMaker jm = new JavaMaker(superclass, interfaces, @@ -84,11 +68,7 @@ try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); jm.build(bytes); - if (customProxyName != null) { - Py.saveClassFile(fullProxyName, bytes, Py.getSystemState().javaproxy_dir); - } else { - Py.saveClassFile(fullProxyName, bytes); - } + Py.saveClassFile(fullProxyName, bytes); return makeClass(superclass, vinterfaces, jm.myClass, bytes); } catch (Exception exc) { Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/src/org/python/core/Py.java 2009-08-23 19:47:55 UTC (rev 6713) @@ -839,9 +839,8 @@ public static void initProxy(PyProxy proxy, String module, String pyclass, Object[] args) { - if (proxy._getPyInstance() != null) { + if (proxy._getPyInstance() != null) return; - } ThreadState ts = getThreadState(); PyObject instance = ts.getInitializingProxy(); if (instance != null) { @@ -1781,17 +1780,12 @@ } public static void saveClassFile(String name, ByteArrayOutputStream bytestream) { - saveClassFile(name, bytestream, Options.proxyDebugDirectory); - } - - public static void saveClassFile(String name, ByteArrayOutputStream baos, String dirname) { + String dirname = Options.proxyDebugDirectory; if (dirname == null) { return; } - saveClassFile(name, baos.toByteArray(), dirname); - } - public static void saveClassFile(String name, byte[] bytes, String dirname) { + byte[] bytes = bytestream.toByteArray(); File dir = new File(dirname); File file = makeFilename(name, dir); new File(file.getParent()).mkdirs(); Modified: trunk/jython/src/org/python/core/PyJavaType.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaType.java 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/src/org/python/core/PyJavaType.java 2009-08-23 19:47:55 UTC (rev 6713) @@ -186,7 +186,7 @@ underlying_class = forClass; computeLinearMro(baseClass); } else { - needsInners.add(this); + needsInners.add(this); javaProxy = forClass; objtype = PyType.fromClassSkippingInners(Class.class, needsInners); // Wrapped Java types fill in their mro first using all of their interfaces then their Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/src/org/python/core/PySystemState.java 2009-08-23 19:47:55 UTC (rev 6713) @@ -40,7 +40,6 @@ public static final String PYTHON_CACHEDIR_SKIP = "python.cachedir.skip"; public static final String PYTHON_CONSOLE_ENCODING = "python.console.encoding"; protected static final String CACHEDIR_DEFAULT_NAME = "cachedir"; - public static final String PYTHON_JAVAPROXYDIR = "python.javaproxydir"; public static final String JYTHON_JAR = "jython.jar"; public static final String JYTHON_DEV_JAR = "jython-dev.jar"; @@ -139,13 +138,6 @@ public PyObject last_type = Py.None; public PyObject last_traceback = Py.None; - private static String defaultJavaProxyDir; - - /** - * The directory where named Java proxies are written. - */ - public String javaproxy_dir; - public PyObject __name__ = new PyString("sys"); public PyObject __dict__; @@ -197,8 +189,6 @@ __dict__.invoke("update", getType().fastGetDict()); __dict__.__setitem__("displayhook", __displayhook__); __dict__.__setitem__("excepthook", __excepthook__); - - javaproxy_dir = defaultJavaProxyDir; } void reload() throws PyIgnoreMethodTag { @@ -867,8 +857,6 @@ // other initializations initBuiltins(registry); initStaticFields(); - defaultJavaProxyDir = registry.getProperty(PYTHON_JAVAPROXYDIR); - // Initialize the path (and add system defaults) defaultPath = initPath(registry, standalone, jarFileName); defaultArgv = initArgv(argv); Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/src/org/python/core/PyType.java 2009-08-23 19:47:55 UTC (rev 6713) @@ -579,9 +579,11 @@ if (module != null) { proxyName = module.toString() + "$" + proxyName; } - javaProxy = MakeProxies.makeProxy(baseProxyClass, interfaces, name, proxyName, dict); + Class<?> proxyClass = MakeProxies.makeProxy(baseProxyClass, interfaces, name, proxyName, + dict); + javaProxy = proxyClass; - PyType proxyType = PyType.fromClass((Class<?>)javaProxy); + PyType proxyType = PyType.fromClass(proxyClass); List<PyObject> cleanedBases = Generic.list(); boolean addedProxyType = false; for (PyObject base : bases) { Modified: trunk/jython/src/org/python/core/util/StringUtil.java =================================================================== --- trunk/jython/src/org/python/core/util/StringUtil.java 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/src/org/python/core/util/StringUtil.java 2009-08-23 19:47:55 UTC (rev 6713) @@ -3,10 +3,8 @@ import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; -import java.util.Set; import org.python.core.Py; -import org.python.util.Generic; /** * String Utility methods. @@ -86,47 +84,4 @@ chars[0] = Character.toLowerCase(c0); return new String(chars); } - - /** - * Returns true if each segment of <code>name</code> produced by splitting it on '.' is a valid - * Java identifier. - */ - public static boolean isJavaClassName(String name) { - for (String segment : name.split("\\.")) { - if (!isJavaIdentifier(segment)) { - return false; - } - } - return true; - } - - /** - * Returns true if ident is a valid Java identifier as defined by - * http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#40625 - */ - public static boolean isJavaIdentifier(String ident) { - if (ident.length() == 0 || JAVA_LITERALS.contains(ident)) { - return false; - } - int cp = ident.codePointAt(0); - if (!Character.isJavaIdentifierStart(cp)) { - return false; - } - for (int i = Character.charCount(cp); i < ident.length(); i += Character.charCount(cp)) { - cp = ident.codePointAt(i); - if (!Character.isJavaIdentifierPart(cp)) { - return false; - } - } - return true; - } - - // True false and null are just literals, the rest are keywords - private static final Set<String> JAVA_LITERALS = Generic.set("abstract", "continue", "for", - "new", "switch", "assert", "default", "goto", "package", "synchronized", "boolean", "do", - "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", - "else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", - "class", "finally", "long", "strictfp", "volatile", "const", "float", "native", "super", - "while", "true", "false", "null"); } Modified: trunk/jython/src/org/python/expose/generate/ExposeTask.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ExposeTask.java 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/src/org/python/expose/generate/ExposeTask.java 2009-08-23 19:47:55 UTC (rev 6713) @@ -8,8 +8,8 @@ import org.apache.tools.ant.BuildException; import org.objectweb.asm.ClassWriter; +import org.python.core.Py; import org.python.core.Options; -import org.python.core.Py; import org.python.util.GlobMatchingTask; public class ExposeTask extends GlobMatchingTask { Deleted: trunk/jython/src/org/python/util/CompileProxiesTask.java =================================================================== --- trunk/jython/src/org/python/util/CompileProxiesTask.java 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/src/org/python/util/CompileProxiesTask.java 2009-08-23 19:47:55 UTC (rev 6713) @@ -1,68 +0,0 @@ -package org.python.util; - -import java.io.File; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import org.apache.tools.ant.BuildException; -import org.python.core.Py; -import org.python.core.PySystemState; - -/** - * Compiles the Java proxies for Python classes in the Python modules in a given directory tree to - * another directory. - */ -public class CompileProxiesTask extends JycompileAntTask { - - @Override - public void process(Set<File> toCompile) throws BuildException { - // Run our superclass' compile first to check that everything has valid syntax before - // attempting to import it and to keep the imports from generating class files in the source - // directory - super.process(toCompile); - Properties props = new Properties(); - props.setProperty(PySystemState.PYTHON_CACHEDIR_SKIP, "true"); - PySystemState.initialize(props, null); - PySystemState sys = Py.getSystemState(); - // Part 2 of not spewing compilation in the source directory: import our compiled files - sys.path.insert(0, Py.newString(destDir.getAbsolutePath())); - sys.javaproxy_dir = destDir.getAbsolutePath(); - PythonInterpreter interp = new PythonInterpreter(); - for (String module : compiledModuleNames) { - try { - interp.exec("import " + module); - } catch (RuntimeException t) { - // We didn't get to import any of these files, so their compiled form can't hang - // around or we won't pick them up as needing compilation next time. - for (File f : compiledModuleFiles) { - f.delete(); - } - throw t; - } - // This module was successfully imported, so its compiled file can hang around - compiledModuleFiles.remove(0); - } - } - - @Override - protected void compile(File src, File compiled, String moduleName) { - try { - super.compile(src, compiled, moduleName); - } catch (BuildException ex) { - // This depends on the modtime of the source being newer than that of the compiled file - // to decide to do the import in process, so even though these files compiled properly, - // they need to be deleted to allow them to be imported in process next time around. - for (File f : compiledModuleFiles) { - f.delete(); - } - throw ex; - } - compiledModuleNames.add(moduleName); - compiledModuleFiles.add(compiled); - } - - private List<String> compiledModuleNames = Generic.list(); - - private List<File> compiledModuleFiles = Generic.list(); -} Deleted: trunk/jython/src/org/python/util/FileNameMatchingTask.java =================================================================== --- trunk/jython/src/org/python/util/FileNameMatchingTask.java 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/src/org/python/util/FileNameMatchingTask.java 2009-08-23 19:47:55 UTC (rev 6713) @@ -1,95 +0,0 @@ -package org.python.util; - -import java.io.File; -import java.util.Set; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.taskdefs.MatchingTask; -import org.apache.tools.ant.types.Path; -import org.apache.tools.ant.util.FileNameMapper; -import org.apache.tools.ant.util.SourceFileScanner; - -public abstract class FileNameMatchingTask extends MatchingTask { - - private Path src; - - protected File destDir; - - private Set<File> toProcess = Generic.set(); - - /** - * Set the source directories to find the class files to be exposed. - */ - public void setSrcdir(Path srcDir) { - if (src == null) { - src = srcDir; - } else { - src.append(srcDir); - } - } - - /** - * Gets the source dirs to find the class files to be exposed. - */ - public Path getSrcdir() { - return src; - } - - /** - * Set the destination directory into which the Java source files should be compiled. - * - * @param destDir - * the destination director - */ - public void setDestdir(File destDir) { - this.destDir = destDir; - } - - /** - * Gets the destination directory into which the java source files should be compiled. - * - * @return the destination directory - */ - public File getDestdir() { - return destDir; - } - - @Override - public void execute() throws BuildException { - checkParameters(); - toProcess.clear(); - for (String srcEntry : src.list()) { - File srcDir = getProject().resolveFile(srcEntry); - if (!srcDir.exists()) { - throw new BuildException("srcdir '" + srcDir.getPath() + "' does not exist!", - getLocation()); - } - String[] files = getDirectoryScanner(srcDir).getIncludedFiles(); - scanDir(srcDir, destDir != null ? destDir : srcDir, files); - } - process(toProcess); - } - - protected abstract void process(Set<File> matches); - - protected abstract FileNameMapper createMapper(); - - protected void scanDir(File srcDir, File destDir, String[] files) { - SourceFileScanner sfs = new SourceFileScanner(this); - for (File file : sfs.restrictAsFiles(files, srcDir, destDir, createMapper())) { - toProcess.add(file); - } - } - /** - * Check that all required attributes have been set and nothing silly has been entered. - */ - protected void checkParameters() throws BuildException { - if (src == null || src.size() == 0) { - throw new BuildException("srcdir attribute must be set!", getLocation()); - } - if (destDir != null && !destDir.isDirectory()) { - throw new BuildException("destination directory '" + destDir + "' does not exist " - + "or is not a directory", getLocation()); - } - } -} \ No newline at end of file Modified: trunk/jython/src/org/python/util/GlobMatchingTask.java =================================================================== --- trunk/jython/src/org/python/util/GlobMatchingTask.java 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/src/org/python/util/GlobMatchingTask.java 2009-08-23 19:47:55 UTC (rev 6713) @@ -1,19 +1,101 @@ package org.python.util; -import org.apache.tools.ant.util.FileNameMapper; +import java.io.File; +import java.util.Set; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.taskdefs.MatchingTask; +import org.apache.tools.ant.types.Path; import org.apache.tools.ant.util.GlobPatternMapper; +import org.apache.tools.ant.util.SourceFileScanner; -public abstract class GlobMatchingTask extends FileNameMatchingTask { +public abstract class GlobMatchingTask extends MatchingTask { + private Path src; + + protected File destDir; + + private Set<File> toExpose = Generic.set(); + + /** + * Set the source directories to find the class files to be exposed. + */ + public void setSrcdir(Path srcDir) { + if (src == null) { + src = srcDir; + } else { + src.append(srcDir); + } + } + + /** + * Gets the source dirs to find the class files to be exposed. + */ + public Path getSrcdir() { + return src; + } + + /** + * Set the destination directory into which the Java source files should be compiled. + * + * @param destDir + * the destination director + */ + public void setDestdir(File destDir) { + this.destDir = destDir; + } + + /** + * Gets the destination directory into which the java source files should be compiled. + * + * @return the destination directory + */ + public File getDestdir() { + return destDir; + } + @Override - protected FileNameMapper createMapper() { - FileNameMapper mapper = new GlobPatternMapper(); - mapper.setFrom(getFrom()); - mapper.setTo(getTo()); - return mapper; + public void execute() throws BuildException { + checkParameters(); + toExpose.clear(); + for (String srcEntry : src.list()) { + File srcDir = getProject().resolveFile(srcEntry); + if (!srcDir.exists()) { + throw new BuildException("srcdir '" + srcDir.getPath() + "' does not exist!", + getLocation()); + } + String[] files = getDirectoryScanner(srcDir).getIncludedFiles(); + scanDir(srcDir, destDir != null ? destDir : srcDir, files); + } + process(toExpose); } + protected abstract void process(Set<File> matches); + protected abstract String getFrom(); protected abstract String getTo(); -} + + protected void scanDir(File srcDir, File destDir, String[] files) { + GlobPatternMapper m = new GlobPatternMapper(); + m.setFrom(getFrom()); + m.setTo(getTo()); + SourceFileScanner sfs = new SourceFileScanner(this); + for (File file : sfs.restrictAsFiles(files, srcDir, destDir, m)) { + toExpose.add(file); + } + } + + /** + * Check that all required attributes have been set and nothing silly has been entered. + */ + protected void checkParameters() throws BuildException { + if (src == null || src.size() == 0) { + throw new BuildException("srcdir attribute must be set!", getLocation()); + } + if (destDir != null && !destDir.isDirectory()) { + throw new BuildException("destination directory '" + destDir + "' does not exist " + + "or is not a directory", getLocation()); + } + } +} \ No newline at end of file Modified: trunk/jython/src/org/python/util/JycompileAntTask.java =================================================================== --- trunk/jython/src/org/python/util/JycompileAntTask.java 2009-08-23 19:05:32 UTC (rev 6712) +++ trunk/jython/src/org/python/util/JycompileAntTask.java 2009-08-23 19:47:55 UTC (rev 6713) @@ -59,12 +59,10 @@ imp.cacheCompiledSource(src.getAbsolutePath(), compiled.getAbsolutePath(), bytes); } - @Override protected String getFrom() { return "*.py"; } - @Override protected String getTo() { return "*$py.class"; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-09-01 13:59:21
|
Revision: 6738 http://jython.svn.sourceforge.net/jython/?rev=6738&view=rev Author: fwierzbicki Date: 2009-09-01 13:59:14 +0000 (Tue, 01 Sep 2009) Log Message: ----------- Update version numbers. Modified Paths: -------------- trunk/jython/NEWS trunk/jython/build.xml Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-09-01 13:57:52 UTC (rev 6737) +++ trunk/jython/NEWS 2009-09-01 13:59:14 UTC (rev 6738) @@ -1,6 +1,6 @@ Jython NEWS -Jython 2.5.1 +Jython 2.5.1rc1 New Features - Upgraded to ANTLR 3.1.3 - [ 1859477 ] Dynamically loaded ServletFilters like PyServlet Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2009-09-01 13:57:52 UTC (rev 6737) +++ trunk/jython/build.xml 2009-09-01 13:59:14 UTC (rev 6738) @@ -128,7 +128,7 @@ <property name="jython.version.noplus" value="2.5.0"/> <property name="jython.major_version" value="2"/> <property name="jython.minor_version" value="5"/> - <property name="jython.micro_version" value="0"/> + <property name="jython.micro_version" value="1"/> <property name="jython.release_level" value="${PY_RELEASE_LEVEL_FINAL}"/> <property name="jython.release_serial" value="0"/> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2009-09-07 20:41:58
|
Revision: 6762 http://jython.svn.sourceforge.net/jython/?rev=6762&view=rev Author: zyasoft Date: 2009-09-07 20:41:45 +0000 (Mon, 07 Sep 2009) Log Message: ----------- Fixed regression where threading._Lock, _RLock were no longer available as synonyms to Lock and RLock respectively, which Twisted needs. Added a test case to prevent recurrence. This resolves #1079. Modified Paths: -------------- trunk/jython/Lib/test/test_threading_jy.py trunk/jython/Lib/threading.py trunk/jython/NEWS trunk/jython/src/org/python/modules/_threading/_threading.java Modified: trunk/jython/Lib/test/test_threading_jy.py =================================================================== --- trunk/jython/Lib/test/test_threading_jy.py 2009-09-06 23:26:58 UTC (rev 6761) +++ trunk/jython/Lib/test/test_threading_jy.py 2009-09-07 20:41:45 UTC (rev 6762) @@ -36,8 +36,14 @@ time.sleep(random.random()) +class TwistedTestCase(unittest.TestCase): + + def test_needs_underscored_versions(self): + self.assertEqual(threading.Lock, threading._Lock) + self.assertEqual(threading.RLock, threading._RLock) + def test_main(): - test_support.run_unittest(ThreadingTestCase) + test_support.run_unittest(ThreadingTestCase, TwistedTestCase) if __name__ == "__main__": Modified: trunk/jython/Lib/threading.py =================================================================== --- trunk/jython/Lib/threading.py 2009-09-06 23:26:58 UTC (rev 6761) +++ trunk/jython/Lib/threading.py 2009-09-07 20:41:45 UTC (rev 6762) @@ -5,7 +5,7 @@ from org.python.util import jython from thread import _newFunctionThread from thread import _local as local -from _threading import Lock, RLock, Condition +from _threading import Lock, RLock, Condition, _Lock, _RLock import java.lang.Thread import weakref Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-09-06 23:26:58 UTC (rev 6761) +++ trunk/jython/NEWS 2009-09-07 20:41:45 UTC (rev 6762) @@ -1,5 +1,9 @@ Jython NEWS +Jython 2.5.1rc2 + Bugs Fixed + - [ 1079 ] fixed regression on issue: twisted.python.threadable module: missing attribute '_RLock' + Jython 2.5.1rc1 New Features - Upgraded to ANTLR 3.1.3 Modified: trunk/jython/src/org/python/modules/_threading/_threading.java =================================================================== --- trunk/jython/src/org/python/modules/_threading/_threading.java 2009-09-06 23:26:58 UTC (rev 6761) +++ trunk/jython/src/org/python/modules/_threading/_threading.java 2009-09-07 20:41:45 UTC (rev 6762) @@ -10,6 +10,8 @@ dict.__setitem__("__name__", Py.newString("_threading")); dict.__setitem__("Lock", Lock.TYPE); dict.__setitem__("RLock", Lock.TYPE); + dict.__setitem__("_Lock", Lock.TYPE); + dict.__setitem__("_RLock", Lock.TYPE); dict.__setitem__("Condition", Condition.TYPE); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2009-09-07 21:48:27
|
Revision: 6763 http://jython.svn.sourceforge.net/jython/?rev=6763&view=rev Author: zyasoft Date: 2009-09-07 21:48:20 +0000 (Mon, 07 Sep 2009) Log Message: ----------- CodeCompiler#visitAssert now looks up the AssertionError by using PyFrame#getglobal, so user code can redefine the behavior of assert. Fixes #1461 Bumped bytecode magic. Modified Paths: -------------- trunk/jython/NEWS trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/core/imp.java Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-09-07 20:41:45 UTC (rev 6762) +++ trunk/jython/NEWS 2009-09-07 21:48:20 UTC (rev 6763) @@ -3,6 +3,7 @@ Jython 2.5.1rc2 Bugs Fixed - [ 1079 ] fixed regression on issue: twisted.python.threadable module: missing attribute '_RLock' + - [ 1461 ] assert statement should lookup AssertionError using getglobal Jython 2.5.1rc1 New Features Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-09-07 20:41:45 UTC (rev 6762) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-09-07 21:48:20 UTC (rev 6763) @@ -964,8 +964,9 @@ getNone(); } - /* Push exception type onto stack(Py.AssertionError) */ - code.getstatic("org/python/core/Py", "AssertionError", "Lorg/python/core/PyObject;"); + /* Push exception type onto stack(AssertionError) */ + loadFrame(); + emitGetGlobal("AssertionError"); code.swap(); // The type is the first argument, but the message could be a yield Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2009-09-07 20:41:45 UTC (rev 6762) +++ trunk/jython/src/org/python/core/imp.java 2009-09-07 21:48:20 UTC (rev 6763) @@ -21,7 +21,7 @@ private static final String UNKNOWN_SOURCEFILE = "<unknown>"; - private static final int APIVersion = 25; + private static final int APIVersion = 26; public static final int NO_MTIME = -1; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-09-09 02:59:02
|
Revision: 6766 http://jython.svn.sourceforge.net/jython/?rev=6766&view=rev Author: pjenvey Date: 2009-09-09 02:58:36 +0000 (Wed, 09 Sep 2009) Log Message: ----------- don't assume posix fixes #1425 thanks Matthew L Daniel Modified Paths: -------------- trunk/jython/Lib/distutils/util.py trunk/jython/NEWS Modified: trunk/jython/Lib/distutils/util.py =================================================================== --- trunk/jython/Lib/distutils/util.py 2009-09-08 19:18:26 UTC (rev 6765) +++ trunk/jython/Lib/distutils/util.py 2009-09-09 02:58:36 UTC (rev 6766) @@ -155,25 +155,26 @@ Otherwise, it requires making 'pathname' relative and then joining the two, which is tricky on DOS/Windows and Mac OS. """ - if os.name == 'posix' or os.name == 'java': + os_name = os._name if sys.platform.startswith('java') else os.name + if os_name == 'posix': if not os.path.isabs(pathname): return os.path.join(new_root, pathname) else: return os.path.join(new_root, pathname[1:]) - elif os.name == 'nt': + elif os_name == 'nt': (drive, path) = os.path.splitdrive(pathname) if path[0] == '\\': path = path[1:] return os.path.join(new_root, path) - elif os.name == 'os2': + elif os_name == 'os2': (drive, path) = os.path.splitdrive(pathname) if path[0] == os.sep: path = path[1:] return os.path.join(new_root, path) - elif os.name == 'mac': + elif os_name == 'mac': if not os.path.isabs(pathname): return os.path.join(new_root, pathname) else: @@ -184,7 +185,7 @@ else: raise DistutilsPlatformError, \ - "nothing known about platform '%s'" % os.name + "nothing known about platform '%s'" % os_name _environ_checked = 0 Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-09-08 19:18:26 UTC (rev 6765) +++ trunk/jython/NEWS 2009-09-09 02:58:36 UTC (rev 6766) @@ -4,6 +4,7 @@ Bugs Fixed - [ 1079 ] fixed regression on issue: twisted.python.threadable module: missing attribute '_RLock' - [ 1461 ] assert statement should lookup AssertionError using getglobal + - [ 1425 ] distutils/util.py assumes too much posix Jython 2.5.1rc1 New Features This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-09-09 03:24:25
|
Revision: 6768 http://jython.svn.sourceforge.net/jython/?rev=6768&view=rev Author: pjenvey Date: 2009-09-09 03:24:04 +0000 (Wed, 09 Sep 2009) Log Message: ----------- fix array.to/fromfile on files in + mode fixes #1457 Modified Paths: -------------- trunk/jython/Lib/test/test_array_jy.py trunk/jython/src/org/python/core/PyArray.java Modified: trunk/jython/Lib/test/test_array_jy.py =================================================================== --- trunk/jython/Lib/test/test_array_jy.py 2009-09-09 03:06:20 UTC (rev 6767) +++ trunk/jython/Lib/test/test_array_jy.py 2009-09-09 03:24:04 UTC (rev 6768) @@ -1,6 +1,7 @@ # The jarray module is being phased out, with all functionality # now available in the array module. - +from __future__ import with_statement +import os import unittest from test import test_support from array import array, zeros @@ -11,7 +12,6 @@ class ArrayJyTestCase(unittest.TestCase): def test_jarray(self): # until it is fully formally removed - # 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 @@ -44,8 +44,34 @@ Color.RGBtoHSB(0, 255, 255, hsb1) self.assertEqual(hsb, hsb1, "hsb float arrays were not equal") + +class ToFromfileTestCase(unittest.TestCase): + + def tearDown(self): + if os.path.exists(test_support.TESTFN): + os.remove(test_support.TESTFN) + + def test_tofromfile(self): + # http://bugs.jython.org/issue1457 + x = array('i', range(5)) + with open(test_support.TESTFN, 'wb') as f: + x.tofile(f) + + x = array('i', []) + with open(test_support.TESTFN, 'r+b') as f: + x.fromfile(f, 5) + x *= 2 + x.tofile(f) + + with open(test_support.TESTFN, 'rb') as f: + x.fromfile(f, 10) + self.assertEqual(x, array('i', range(5) * 4)) + + def test_main(): - test_support.run_unittest(ArrayJyTestCase) + test_support.run_unittest(ArrayJyTestCase, + ToFromfileTestCase) + if __name__ == "__main__": test_main() Modified: trunk/jython/src/org/python/core/PyArray.java =================================================================== --- trunk/jython/src/org/python/core/PyArray.java 2009-09-09 03:06:20 UTC (rev 6767) +++ trunk/jython/src/org/python/core/PyArray.java 2009-09-09 03:24:04 UTC (rev 6768) @@ -802,15 +802,10 @@ */ public void fromfile(PyObject f, int count) { // check for arg1 as file object - if(!(f instanceof PyFile)) { + if (!(f instanceof PyFile)) { throw Py.TypeError("arg1 must be open file"); } PyFile file = (PyFile)f; - // check for read only - if(file.mode.indexOf("r") == -1) { - throw Py.TypeError("file needs to be in read mode"); - } - // read the data via the PyFile int readbytes = count * getStorageSize(); String buffer = file.read(readbytes).toString(); // load whatever was collected into the array @@ -1588,13 +1583,10 @@ * Python builtin file object to write data */ public void tofile(PyObject f) { - if(!(f instanceof PyFile)) + if (!(f instanceof PyFile)) { throw Py.TypeError("arg must be open file"); - PyFile file = (PyFile)f; - if(file.mode.indexOf("w") == -1 && file.mode.indexOf("a") == -1) { - throw Py.TypeError("file needs to be in write or append mode"); } - // write via the PyFile + PyFile file = (PyFile)f; file.write(tostring()); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-09-09 03:45:49
|
Revision: 6769 http://jython.svn.sourceforge.net/jython/?rev=6769&view=rev Author: pjenvey Date: 2009-09-09 03:45:43 +0000 (Wed, 09 Sep 2009) Log Message: ----------- fix __cmp__ specifying the wrong array type to lookup_where triggering an ArrayStoreException in some cases fixes #1382 Modified Paths: -------------- trunk/jython/Lib/test/test_cmp_jy.py trunk/jython/NEWS trunk/jython/src/templates/object.derived Modified: trunk/jython/Lib/test/test_cmp_jy.py =================================================================== --- trunk/jython/Lib/test/test_cmp_jy.py 2009-09-09 03:24:04 UTC (rev 6768) +++ trunk/jython/Lib/test/test_cmp_jy.py 2009-09-09 03:45:43 UTC (rev 6769) @@ -1,7 +1,18 @@ "Tests for cmp() compatibility with CPython" +import UserDict import unittest from test import test_support +class CmpGeneralTestCase(unittest.TestCase): + + def test_type_crash(self): + # Used to throw ArrayStoreException: + # http://bugs.jython.org/issue1382 + class Configuration(object, UserDict.DictMixin): + pass + self.assertNotEqual(Configuration(), None) + + class UnicodeDerivedCmp(unittest.TestCase): "Test for http://bugs.jython.org/issue1889394" def testCompareWithString(self): @@ -14,6 +25,7 @@ class B(unicode): pass self.assertEqual(A(), B()) + class LongDerivedCmp(unittest.TestCase): def testCompareWithString(self): class Test(long): @@ -21,6 +33,7 @@ self.assertNotEqual(Test(0), 'foo') self.assertTrue('foo' in [Test(12), 'foo']) + class IntStrCmp(unittest.TestCase): def testIntStrCompares(self): assert not (-1 > 'a') @@ -31,6 +44,7 @@ assert (-2 < 'a') assert not (-1 == 'a') + class CustomCmp(unittest.TestCase): def test___cmp___returns(self): class Foo(object): @@ -63,13 +77,16 @@ __eq__ = lambda self, other: True self.assertEqual(cmp(Foo(), Bar()), 1) + def test_main(): test_support.run_unittest( + CmpGeneralTestCase, UnicodeDerivedCmp, LongDerivedCmp, IntStrCmp, CustomCmp ) + if __name__ == '__main__': test_main() Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-09-09 03:24:04 UTC (rev 6768) +++ trunk/jython/NEWS 2009-09-09 03:45:43 UTC (rev 6769) @@ -5,6 +5,8 @@ - [ 1079 ] fixed regression on issue: twisted.python.threadable module: missing attribute '_RLock' - [ 1461 ] assert statement should lookup AssertionError using getglobal - [ 1425 ] distutils/util.py assumes too much posix + - [ 1457 ] Cannot write an array in a file opened in r+b mode. + - [ 1382 ] __cmp__ on certain types raises ArrayStoreException Jython 2.5.1rc1 New Features Modified: trunk/jython/src/templates/object.derived =================================================================== --- trunk/jython/src/templates/object.derived 2009-09-09 03:24:04 UTC (rev 6768) +++ trunk/jython/src/templates/object.derived 2009-09-09 03:45:43 UTC (rev 6769) @@ -99,7 +99,7 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyType[] where_type = new PyType[1]; + PyObject[] where_type = new PyObject[1]; PyObject impl = self_type.lookup_where("__cmp__", where_type); // Full Compatibility with CPython __cmp__: // If the derived type don't override __cmp__, the This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-09-09 04:16:57
|
Revision: 6771 http://jython.svn.sourceforge.net/jython/?rev=6771&view=rev Author: pjenvey Date: 2009-09-09 04:16:49 +0000 (Wed, 09 Sep 2009) Log Message: ----------- allow hashlib updating from arrays fixes #1443 Modified Paths: -------------- trunk/jython/Lib/test/test_hashlib_jy.py trunk/jython/NEWS trunk/jython/src/org/python/modules/_hashlib.java Modified: trunk/jython/Lib/test/test_hashlib_jy.py =================================================================== --- trunk/jython/Lib/test/test_hashlib_jy.py 2009-09-09 03:47:22 UTC (rev 6770) +++ trunk/jython/Lib/test/test_hashlib_jy.py 2009-09-09 04:16:49 UTC (rev 6771) @@ -5,6 +5,7 @@ """ import hashlib import unittest +from array import array from test import test_support class HashlibTestCase(unittest.TestCase): @@ -14,7 +15,14 @@ 'acbd18db4cc2f85cedef654fccc4a4d8') self.assertRaises(UnicodeEncodeError, hashlib.md5, u'Gráin amháiñ') + def test_array(self): + self.assertEqual(hashlib.sha1(array('c', 'hovercraft')).hexdigest(), + '496df4d8de2c71973d7e917c4fbe57e6ad46d738') + intarray = array('i', range(5)) + self.assertEqual(hashlib.sha1(intarray).hexdigest(), + hashlib.sha1(intarray.tostring()).hexdigest()) + def test_main(): test_support.run_unittest(HashlibTestCase) Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-09-09 03:47:22 UTC (rev 6770) +++ trunk/jython/NEWS 2009-09-09 04:16:49 UTC (rev 6771) @@ -7,6 +7,7 @@ - [ 1425 ] distutils/util.py assumes too much posix - [ 1457 ] Cannot write an array in a file opened in r+b mode. - [ 1382 ] __cmp__ on certain types raises ArrayStoreException + - [ 1443 ] Can't update() hashlib.sha1() with array.array('c') Jython 2.5.1rc1 New Features Modified: trunk/jython/src/org/python/modules/_hashlib.java =================================================================== --- trunk/jython/src/org/python/modules/_hashlib.java 2009-09-09 03:47:22 UTC (rev 6770) +++ trunk/jython/src/org/python/modules/_hashlib.java 2009-09-09 04:16:49 UTC (rev 6771) @@ -8,6 +8,7 @@ import org.python.core.ClassDictInit; import org.python.core.Py; +import org.python.core.PyArray; import org.python.core.PyObject; import org.python.core.PyString; import org.python.core.PyType; @@ -168,15 +169,19 @@ @ExposedMethod final void HASH_update(PyObject obj) { - if (!(obj instanceof PyString)) { + String string; + if (obj instanceof PyUnicode) { + string = ((PyUnicode)obj).encode(); + } else if (obj instanceof PyString) { + string = obj.toString(); + } else if (obj instanceof PyArray) { + string = ((PyArray)obj).tostring(); + } + else { throw Py.TypeError("update() argument 1 must be string or read-only buffer, not " + obj.getType().fastGetName()); } - if (obj instanceof PyUnicode) { - obj = obj.__str__(); - } - byte[] bytes = ((PyString)obj).toBytes(); - digest.update(bytes); + digest.update(StringUtil.toBytes(string)); } public PyObject digest() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-09-09 04:59:27
|
Revision: 6772 http://jython.svn.sourceforge.net/jython/?rev=6772&view=rev Author: pjenvey Date: 2009-09-09 04:59:15 +0000 (Wed, 09 Sep 2009) Log Message: ----------- allow zlib input from arrays fixes #1444 Modified Paths: -------------- trunk/jython/Lib/zlib.py trunk/jython/NEWS Added Paths: ----------- trunk/jython/Lib/test/test_zlib_jy.py Added: trunk/jython/Lib/test/test_zlib_jy.py =================================================================== --- trunk/jython/Lib/test/test_zlib_jy.py (rev 0) +++ trunk/jython/Lib/test/test_zlib_jy.py 2009-09-09 04:59:15 UTC (rev 6772) @@ -0,0 +1,39 @@ +"""Misc zlib tests + +Made for Jython. +""" +import unittest +import zlib +from array import array +from test import test_support + +class ArrayTestCase(unittest.TestCase): + + def test_array(self): + self._test_array(zlib.compress, zlib.decompress) + + def test_array_compressobj(self): + def compress(value): + co = zlib.compressobj() + return co.compress(value) + co.flush() + def decompress(value): + dco = zlib.decompressobj() + return dco.decompress(value) + dco.flush() + self._test_array(compress, decompress) + + def _test_array(self, compress, decompress): + self.assertEqual(compress(array('c', 'jython')), + compress('jython')) + intarray = array('i', range(5)) + self.assertEqual(compress(intarray), + compress(intarray.tostring())) + compressed = array('c', compress('jython')) + self.assertEqual('jython', decompress(compressed)) + + +def test_main(): + test_support.run_unittest(ArrayTestCase) + + +if __name__ == '__main__': + test_main() Modified: trunk/jython/Lib/zlib.py =================================================================== --- trunk/jython/Lib/zlib.py 2009-09-09 04:16:49 UTC (rev 6771) +++ trunk/jython/Lib/zlib.py 2009-09-09 04:59:15 UTC (rev 6772) @@ -13,7 +13,9 @@ Compressor objects support compress() and flush() methods; decompressor objects support decompress() and flush(). """ -import jarray, binascii +import array +import binascii +import jarray from java.util.zip import Adler32, Deflater, Inflater, DataFormatException from java.lang import Long, String @@ -59,13 +61,14 @@ if level < Z_BEST_SPEED or level > Z_BEST_COMPRESSION: raise error, "Bad compression level" deflater = Deflater(level, 0) + string = _to_input(string) deflater.setInput(string, 0, len(string)) deflater.finish() return _get_deflate_data(deflater) def decompress(string, wbits=0, bufsize=16384): inflater = Inflater(wbits < 0) - inflater.setInput(string) + inflater.setInput(_to_input(string)) return _get_inflate_data(inflater) @@ -84,6 +87,7 @@ def compress(self, string): if self._ended: raise error("compressobj may not be used after flush(Z_FINISH)") + string = _to_input(string) self.deflater.setInput(string, 0, len(string)) return _get_deflate_data(self.deflater) @@ -123,6 +127,7 @@ if max_length < 0: raise ValueError("max_length must be a positive integer") + string = _to_input(string) self.inflater.setInput(string) inflated = _get_inflate_data(self.inflater, max_length) @@ -146,6 +151,8 @@ self.inflater.end() return last +def _to_input(string): + return string.tostring() if isinstance(string, array.array) else string def _get_deflate_data(deflater): buf = jarray.zeros(1024, 'b') Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-09-09 04:16:49 UTC (rev 6771) +++ trunk/jython/NEWS 2009-09-09 04:59:15 UTC (rev 6772) @@ -8,6 +8,7 @@ - [ 1457 ] Cannot write an array in a file opened in r+b mode. - [ 1382 ] __cmp__ on certain types raises ArrayStoreException - [ 1443 ] Can't update() hashlib.sha1() with array.array('c') + - [ 1444 ] Can't zlib.compress() with array.array('c') Jython 2.5.1rc1 New Features This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-09-11 05:35:02
|
Revision: 6782 http://jython.svn.sourceforge.net/jython/?rev=6782&view=rev Author: pjenvey Date: 2009-09-11 05:34:56 +0000 (Fri, 11 Sep 2009) Log Message: ----------- o fix PyTuple/List.equals not trying rich comparison (_eq) to all other PyObjects like PyObject.equals does o no need to synchronize all of PyList.equals Modified Paths: -------------- trunk/jython/Lib/test/test_seq_jy.py trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PyTuple.java Modified: trunk/jython/Lib/test/test_seq_jy.py =================================================================== --- trunk/jython/Lib/test/test_seq_jy.py 2009-09-11 05:22:00 UTC (rev 6781) +++ trunk/jython/Lib/test/test_seq_jy.py 2009-09-11 05:34:56 UTC (rev 6782) @@ -27,6 +27,13 @@ self.assertTrue(foo in seq1) self.assertFalse(eq_called) + def test_seq_equality(self): + for type2test in self.types2test: + class Foo(object): + def __eq__(self, other): + return True + self.assertTrue(type2test() in [Foo()]) + def test_seq_subclass_equality(self): # Various combinations of PyObject._eq, overriden Object.equals, # and cmp implementations Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2009-09-11 05:22:00 UTC (rev 6781) +++ trunk/jython/src/org/python/core/PyList.java 2009-09-11 05:34:56 UTC (rev 6782) @@ -953,16 +953,21 @@ } @Override - public synchronized boolean equals(Object other) { + public boolean equals(Object other) { if (this == other) { return true; } - if (other instanceof PyList) { - return _eq((PyList)other).__nonzero__(); - } else if (other instanceof List && !(other instanceof PyTuple)) { - List otherList = (List)other; - return list.equals(otherList); + + if (other instanceof PyObject) { + synchronized (this) { + return _eq((PyObject)other).__nonzero__(); + } } + if (other instanceof List) { + synchronized (this) { + return list.equals(other); + } + } return false; } Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2009-09-11 05:22:00 UTC (rev 6781) +++ trunk/jython/src/org/python/core/PyTuple.java 2009-09-11 05:34:56 UTC (rev 6782) @@ -476,9 +476,11 @@ if (this == other) { return true; } - if (other instanceof PyTuple) { - return _eq((PyTuple)other).__nonzero__(); - } else if (other instanceof List && !(other instanceof PyList)) { + + if (other instanceof PyObject) { + return _eq((PyObject)other).__nonzero__(); + } + if (other instanceof List) { return other.equals(this); } return false; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2009-09-11 06:55:49
|
Revision: 6785 http://jython.svn.sourceforge.net/jython/?rev=6785&view=rev Author: cgroves Date: 2009-09-11 06:55:34 +0000 (Fri, 11 Sep 2009) Log Message: ----------- Use the builtin codecs when nothing is found in the registry. Fixes issue 1458. Modified Paths: -------------- trunk/jython/NEWS trunk/jython/src/org/python/core/codecs.java Added Paths: ----------- trunk/jython/Lib/test/print_sans_lib.py trunk/jython/Lib/test/test_codecs_jy.py Added: trunk/jython/Lib/test/print_sans_lib.py =================================================================== --- trunk/jython/Lib/test/print_sans_lib.py (rev 0) +++ trunk/jython/Lib/test/print_sans_lib.py 2009-09-11 06:55:34 UTC (rev 6785) @@ -0,0 +1,4 @@ +import sys +sys.path = [path for path in sys.path if not path.startswith('/')] +encoded = u'hi'.encode("utf-8") +encoded.decode('utf-8') Added: trunk/jython/Lib/test/test_codecs_jy.py =================================================================== --- trunk/jython/Lib/test/test_codecs_jy.py (rev 0) +++ trunk/jython/Lib/test/test_codecs_jy.py 2009-09-11 06:55:34 UTC (rev 6785) @@ -0,0 +1,19 @@ +import subprocess +import sys +import test_support +import unittest + +class AccessBuiltinCodecs(unittest.TestCase): + def test_print_sans_lib(self): + '''Encodes and decodes using utf-8 after in an environment without the standard library + + Checks that the builtin utf-8 codec is always available: http://bugs.jython.org/issue1458''' + subprocess.call([sys.executable, "-J-Dpython.cachedir.skip=true", + "-J-Dpython.security.respectJavaAccessibility=false", + test_support.findfile('print_sans_lib.py')]) + +def test_main(): + test_support.run_unittest(AccessBuiltinCodecs) + +if __name__ == "__main__": + test_main() Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-09-11 06:44:19 UTC (rev 6784) +++ trunk/jython/NEWS 2009-09-11 06:55:34 UTC (rev 6785) @@ -9,6 +9,7 @@ - [ 1382 ] __cmp__ on certain types raises ArrayStoreException - [ 1443 ] Can't update() hashlib.sha1() with array.array('c') - [ 1444 ] Can't zlib.compress() with array.array('c') + - [ 1458 ] Builtin codecs aren't available without standard lib Jython 2.5.1rc1 New Features Modified: trunk/jython/src/org/python/core/codecs.java =================================================================== --- trunk/jython/src/org/python/core/codecs.java 2009-09-11 06:44:19 UTC (rev 6784) +++ trunk/jython/src/org/python/core/codecs.java 2009-09-11 06:55:34 UTC (rev 6785) @@ -9,6 +9,7 @@ import java.nio.ByteBuffer; import java.nio.charset.Charset; + import java.util.ArrayList; import java.util.Iterator; @@ -113,8 +114,7 @@ } } - public static PyObject decode(PyString v, String encoding, - String errors) { + public static PyObject decode(PyString v, String encoding, String errors) { if (encoding == null) { encoding = getDefaultEncoding(); } else { @@ -127,11 +127,27 @@ /* Shortcut for ascii encoding */ if (encoding.equals("ascii")) { - return new PyUnicode(PyUnicode_DecodeASCII(v.toString(), v.__len__(), errors), true); + return wrapDecodeResult(PyUnicode_DecodeASCII(v.toString(), v.__len__(), errors)); } /* Decode via the codec registry */ - PyObject decoder = lookup(encoding).__getitem__(1); + PyObject decoder; + try { + decoder = lookup(encoding).__getitem__(1); + } catch (PyException ex) { + if (ex.match(Py.LookupError)) { + // If we couldn't find an encoding, see if we have a builtin + if (encoding.equals("utf-8")) { + return wrapDecodeResult(PyUnicode_DecodeUTF8(v.toString(), errors)); + } else if(encoding.equals("utf-7")) { + return wrapDecodeResult(PyUnicode_DecodeUTF7(v.toString(), errors)); + } else if(encoding.equals("latin-1")) { + return wrapDecodeResult(PyUnicode_DecodeLatin1(v.toString(), v.__len__(), + errors)); + } + } + throw ex; + } PyObject result; if (errors != null) { result = decoder.__call__(v, new PyString(errors)); @@ -145,6 +161,10 @@ return result.__getitem__(0); } + private static PyUnicode wrapDecodeResult(String result) { + return new PyUnicode(result, true); + } + public static String encode(PyString v, String encoding, String errors) { if (encoding == null) { @@ -165,8 +185,21 @@ return PyUnicode_EncodeASCII(v.toString(), v.__len__(), errors); } - /* Decode via the codec registry */ - PyObject encoder = lookup(encoding).__getitem__(0); + /* Encode via the codec registry */ + PyObject encoder; + try { + encoder = lookup(encoding).__getitem__(0); + } catch (PyException ex) { + if (ex.match(Py.LookupError)) { + // If we couldn't find an encoding, see if we have a builtin + if (encoding.equals("utf-8")) { + return PyUnicode_EncodeUTF8(v.toString(), errors); + } else if(encoding.equals("utf-7")) { + return codecs.PyUnicode_EncodeUTF7(v.toString(), false, false, errors); + } + } + throw ex; + } PyObject result; if (errors != null) { result = encoder.__call__(v, new PyString(errors)); @@ -181,7 +214,7 @@ if (encoded instanceof PyString) { return encoded.toString(); } else { - throw Py.TypeError("decoder did not return a string/unicode object (type=" + throw Py.TypeError("encoder did not return a string/unicode object (type=" + encoded.getType().fastGetName() + ")"); } } @@ -415,8 +448,7 @@ // note that we follow CPython 2.5 exactly here - it does not support surrogates, // but has to process as-if they are there for replacement purposes // fortunately no one really cares about utf-7 - public static String PyUnicode_DecodeUTF7(String str, - String errors) { + public static String PyUnicode_DecodeUTF7(String str, String errors) { int s = 0; int e = str.length(); boolean inShift = false; @@ -551,9 +583,9 @@ } public static String PyUnicode_EncodeUTF7(String str, - boolean encodeSetO, - boolean encodeWhiteSpace, - String errors) { + boolean encodeSetO, + boolean encodeWhiteSpace, + String errors) { int size = str.length(); if (size == 0) { @@ -786,13 +818,11 @@ return v.toString(); } - public static String PyUnicode_DecodeASCII(String str, int size, - String errors) { + public static String PyUnicode_DecodeASCII(String str, int size, String errors) { return PyUnicode_DecodeIntLimited(str, size, errors, "ascii", 128); } - public static String PyUnicode_DecodeLatin1(String str, int size, - String errors) { + public static String PyUnicode_DecodeLatin1(String str, int size, String errors) { return PyUnicode_DecodeIntLimited(str, size, errors, "latin-1", 256); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-09-12 18:14:26
|
Revision: 6789 http://jython.svn.sourceforge.net/jython/?rev=6789&view=rev Author: fwierzbicki Date: 2009-09-12 18:14:14 +0000 (Sat, 12 Sep 2009) Log Message: ----------- Update versions. Modified Paths: -------------- trunk/jython/README.txt trunk/jython/build.xml Modified: trunk/jython/README.txt =================================================================== --- trunk/jython/README.txt 2009-09-12 02:24:31 UTC (rev 6788) +++ trunk/jython/README.txt 2009-09-12 18:14:14 UTC (rev 6789) @@ -1,9 +1,9 @@ -Welcome to Jython 2.5.1rc1 +Welcome to Jython 2.5.1rc2 ========================== -This is the first release candidate of the 2.5.1 version of Jython. This +This is the second release candidate of the 2.5.1 version of Jython. This release fixes a number of bugs, including some major errors when using -coroutines and when using relative imports. Please see the NEWS file for +coroutines and when using relative imports. Please see the NEWS file for detailed release notes. The release was compiled on Mac OS X with JDK 5 and requires JDK 5 to run. Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2009-09-12 02:24:31 UTC (rev 6788) +++ trunk/jython/build.xml 2009-09-12 18:14:14 UTC (rev 6789) @@ -130,7 +130,7 @@ <property name="jython.minor_version" value="5"/> <property name="jython.micro_version" value="1"/> <property name="jython.release_level" value="${PY_RELEASE_LEVEL_GAMMA}"/> - <property name="jython.release_serial" value="1"/> + <property name="jython.release_serial" value="2"/> <condition property="do.snapshot.build"> <isset property="snapshot.revision" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-09-14 01:05:42
|
Revision: 6796 http://jython.svn.sourceforge.net/jython/?rev=6796&view=rev Author: pjenvey Date: 2009-09-14 01:05:23 +0000 (Mon, 14 Sep 2009) Log Message: ----------- force real O_APPEND for files' 'a' mode by going through FileOutputStream, otherwise emulate it with a performance hit for 'a+' mode fixes #1466 Modified Paths: -------------- trunk/jython/NEWS trunk/jython/src/org/python/core/io/FileIO.java Added Paths: ----------- trunk/jython/Lib/test/test_file_jy.py Added: trunk/jython/Lib/test/test_file_jy.py =================================================================== --- trunk/jython/Lib/test/test_file_jy.py (rev 0) +++ trunk/jython/Lib/test/test_file_jy.py 2009-09-14 01:05:23 UTC (rev 6796) @@ -0,0 +1,39 @@ +"""Misc file tests. + +Made for Jython. +""" +from __future__ import with_statement +import os +import unittest +from test import test_support + +class FileTestCase(unittest.TestCase): + + def tearDown(self): + if os.path.exists(test_support.TESTFN): + os.remove(test_support.TESTFN) + + def test_append(self): + self._test_append('ab') + + def test_appendplus(self): + self._test_append('a+') + + def _test_append(self, mode): + # http://bugs.jython.org/issue1466 + fp1 = open(test_support.TESTFN, 'ab') + fp1.write('test1\n') + fp2 = open(test_support.TESTFN, 'ab') + fp2.write('test2\n') + fp1.close() + fp2.close() + with open(test_support.TESTFN) as fp: + self.assertEqual('test1\ntest2\n', fp.read()) + + +def test_main(): + test_support.run_unittest(FileTestCase) + + +if __name__ == '__main__': + test_main() Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-09-13 23:30:43 UTC (rev 6795) +++ trunk/jython/NEWS 2009-09-14 01:05:23 UTC (rev 6796) @@ -1,5 +1,9 @@ Jython NEWS +Jython 2.5.1rc3 + Bugs Fixed + - [ 1466 ] wrong handling of append only files + Jython 2.5.1rc2 New Features - zxJDBC supports the with-statement: connections are committed or rollbacked; cursors are closed Modified: trunk/jython/src/org/python/core/io/FileIO.java =================================================================== --- trunk/jython/src/org/python/core/io/FileIO.java 2009-09-13 23:30:43 UTC (rev 6795) +++ trunk/jython/src/org/python/core/io/FileIO.java 2009-09-14 01:05:23 UTC (rev 6796) @@ -3,6 +3,7 @@ import java.io.File; import java.io.FileNotFoundException; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -28,21 +29,27 @@ /** The underlying file channel */ private FileChannel fileChannel; - /** The underlying file (if known) */ + /** The underlying RandomAccessFile, if known. May be null */ private RandomAccessFile file; + /** The underlying FileOutputStream, if known. May be null */ + private FileOutputStream fileOutputStream; + /** true if the file is opened for reading ('r') */ - private boolean reading = false; + private boolean reading; /** true if the file is opened for writing ('w', 'a', or '+') */ - private boolean writing = false; + private boolean writing; /** true if the file is in appending mode ('a') */ - private boolean appending = false; + private boolean appending; /** true if the file is opened for reading and writing ('+') */ - private boolean plus = false; + private boolean plus; + /** true if write will emulate O_APPEND mode */ + private boolean emulateAppend; + /** * Construct a FileIO instance for the specified file name. * @@ -55,21 +62,21 @@ */ public FileIO(String name, String mode) { parseMode(mode); + File absPath = new RelativeFile(name); - File fullPath = new RelativeFile(name); - String rafMode = "r" + (writing ? "w" : ""); try { - if (plus && reading && !fullPath.isFile()) { - writing = false; // suppress "permission denied" - throw new FileNotFoundException(""); + if (appending && !reading) { + // Take advantage of FileOutputStream's append mode + fromFileOutputStream(absPath); + } else { + fromRandomAccessFile(absPath); + emulateAppend = appending; } - file = new RandomAccessFile(fullPath, rafMode); - fileChannel = file.getChannel(); } catch (FileNotFoundException fnfe) { - if (fullPath.isDirectory()) { + if (absPath.isDirectory()) { throw Py.IOError(Errno.EISDIR, name); } - if ((writing && !fullPath.canWrite()) + if ((writing && !absPath.canWrite()) || fnfe.getMessage().endsWith("(Permission denied)")) { throw Py.IOError(Errno.EACCES, name); } @@ -144,6 +151,34 @@ } /** + * Open the underlying FileChannel from a RandomAccessFile. + * + * @param absPath The absolute path File to open + */ + private void fromRandomAccessFile(File absPath) throws FileNotFoundException { + String rafMode = "r" + (writing ? "w" : ""); + if (plus && reading && !absPath.isFile()) { + // suppress "permission denied" + writing = false; + throw new FileNotFoundException(""); + } + file = new RandomAccessFile(absPath, rafMode); + fileChannel = file.getChannel(); + } + + /** + * Open the underlying FileChannel from a FileOutputStream in append mode, as opposed + * to a RandomAccessFile, for the use of the OS's underlying O_APPEND mode. This can + * only be used by 'a' (not 'a+') mode. + * + * @param absPath The absolute path File to open + */ + private void fromFileOutputStream(File absPath) throws FileNotFoundException { + fileOutputStream = new FileOutputStream(absPath, true); + fileChannel = fileOutputStream.getChannel(); + } + + /** * Raise a value error due to a mode string not containing exactly * one r/w/a/+ character. * @@ -183,11 +218,11 @@ @Override public boolean isatty() { checkClosed(); - if (file == null) { + if (file == null || fileOutputStream == null) { return false; } try { - return FileUtil.isatty(file.getFD()); + return FileUtil.isatty(file != null ? file.getFD() : fileOutputStream.getFD()); } catch (IOException e) { return false; } @@ -259,7 +294,8 @@ checkClosed(); checkWritable(); try { - return fileChannel.write(buf); + return !emulateAppend ? fileChannel.write(buf) : + fileChannel.write(buf, fileChannel.position()); } catch (IOException ioe) { throw Py.IOError(ioe); } @@ -277,12 +313,33 @@ checkClosed(); checkWritable(); try { - return fileChannel.write(bufs); + return !emulateAppend ? fileChannel.write(bufs) : writeAppend(bufs); } catch (IOException ioe) { throw Py.IOError(ioe); } } + /** + * Write multiple ByteBuffers while emulating O_APPEND mode. + * + * @param bufs an array of ByteBuffers + * @return the number of bytes written as a long + */ + private long writeAppend(ByteBuffer[] bufs) throws IOException { + long count = 0; + int bufCount; + for (ByteBuffer buf : bufs) { + if (!buf.hasRemaining()) { + continue; + } + if ((bufCount = fileChannel.write(buf, fileChannel.position())) == 0) { + break; + } + count += bufCount; + } + return count; + } + @Override public long seek(long pos, int whence) { checkClosed(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-09-26 16:14:57
|
Revision: 6812 http://jython.svn.sourceforge.net/jython/?rev=6812&view=rev Author: fwierzbicki Date: 2009-09-26 16:14:48 +0000 (Sat, 26 Sep 2009) Log Message: ----------- Update README and version numbering. Modified Paths: -------------- trunk/jython/README.txt trunk/jython/build.xml Modified: trunk/jython/README.txt =================================================================== --- trunk/jython/README.txt 2009-09-25 03:13:10 UTC (rev 6811) +++ trunk/jython/README.txt 2009-09-26 16:14:48 UTC (rev 6812) @@ -1,11 +1,10 @@ -Welcome to Jython 2.5.1rc3 -========================== +Welcome to Jython 2.5.1 Final +============================= -This is the third release candidate of the 2.5.1 version of Jython. This -release fixes a number of bugs, including some major errors when using -coroutines and when using relative imports, as well as a potential data loss -bug when writing to files in append mode. Please see the NEWS file for detailed -release notes. +This is the final release of the 2.5.1 version of Jython. This release fixes a +number of bugs, including some major errors when using coroutines and when +using relative imports, as well as a potential data loss bug when writing to +files in append mode. Please see the NEWS file for detailed release notes. The release was compiled on Mac OS X with JDK 5 and requires JDK 5 to run. Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2009-09-25 03:13:10 UTC (rev 6811) +++ trunk/jython/build.xml 2009-09-26 16:14:48 UTC (rev 6812) @@ -129,8 +129,8 @@ <property name="jython.major_version" value="2"/> <property name="jython.minor_version" value="5"/> <property name="jython.micro_version" value="1"/> - <property name="jython.release_level" value="${PY_RELEASE_LEVEL_GAMMA}"/> - <property name="jython.release_serial" value="2"/> + <property name="jython.release_level" value="${PY_RELEASE_LEVEL_FINAL}"/> + <property name="jython.release_serial" value="0"/> <condition property="do.snapshot.build"> <isset property="snapshot.revision" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-09-27 01:34:21
|
Revision: 6814 http://jython.svn.sourceforge.net/jython/?rev=6814&view=rev Author: fwierzbicki Date: 2009-09-27 01:34:11 +0000 (Sun, 27 Sep 2009) Log Message: ----------- Removed unused import from thread.java, expanded javadoc package scan. Modified Paths: -------------- trunk/jython/build.xml trunk/jython/src/org/python/modules/thread/thread.java Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2009-09-26 17:43:16 UTC (rev 6813) +++ trunk/jython/build.xml 2009-09-27 01:34:11 UTC (rev 6814) @@ -647,7 +647,7 @@ source="${jdk.source.version}" public="true" breakiterator="yes" - packagenames="org.python.core, org.python.util, com.ziclix.python.sql, com.xhaus.modjy" + packagenames="org.python.core.*, org.python.util.*, org.python.modules.*, com.ziclix.python.sql, com.xhaus.modjy" windowtitle="Jython API documentation" bottom="<a href='http://www.jython.org' target='_top'>Jython homepage</a>" > Modified: trunk/jython/src/org/python/modules/thread/thread.java =================================================================== --- trunk/jython/src/org/python/modules/thread/thread.java 2009-09-26 17:43:16 UTC (rev 6813) +++ trunk/jython/src/org/python/modules/thread/thread.java 2009-09-27 01:34:11 UTC (rev 6814) @@ -8,7 +8,6 @@ import org.python.core.PyInteger; import org.python.core.PyObject; import org.python.core.PyString; -import org.python.core.PyTableCode; import org.python.core.PyType; import org.python.core.PyTuple; @@ -64,10 +63,10 @@ /** * Interrupts all running threads spawned by the thread module. * - * This works in conjunction with:<ul> - * <li>{@link PyTableCode#call(org.python.core.PyFrame, PyObject)}: - * checks for the interrupted status of the current thread and raise - * a SystemRestart exception if a interruption is detected.</li> + * This works in conjunction with:<ul> <li> + * {@link org.python.core.PyTableCode#call}: checks for the interrupted + * status of the current thread and raise a SystemRestart exception if a + * interruption is detected.</li> * <li>{@link FunctionThread#run()}: exits the current thread when a * SystemRestart exception is not caught.</li> * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-01 01:13:24
|
Revision: 6816 http://jython.svn.sourceforge.net/jython/?rev=6816&view=rev Author: pjenvey Date: 2009-10-01 01:13:04 +0000 (Thu, 01 Oct 2009) Log Message: ----------- correct the callable check fixes #1478 Modified Paths: -------------- trunk/jython/NEWS trunk/jython/src/org/python/modules/_collections/PyDefaultDict.java Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-10-01 01:06:20 UTC (rev 6815) +++ trunk/jython/NEWS 2009-10-01 01:13:04 UTC (rev 6816) @@ -1,5 +1,9 @@ Jython NEWS +Jython 2.5.2a1 + Bugs Fixed + - [ 1478 ] defaultdict & weakref.WeakKeyDictionary [TypeError: first argument must be callable] + Jython 2.5.1rc3 Bugs Fixed - [ 1466 ] wrong handling of append only files Modified: trunk/jython/src/org/python/modules/_collections/PyDefaultDict.java =================================================================== --- trunk/jython/src/org/python/modules/_collections/PyDefaultDict.java 2009-10-01 01:06:20 UTC (rev 6815) +++ trunk/jython/src/org/python/modules/_collections/PyDefaultDict.java 2009-10-01 01:13:04 UTC (rev 6816) @@ -54,7 +54,7 @@ int nargs = args.length - kwds.length; if (nargs != 0) { defaultFactory = args[0]; - if (defaultFactory.__findattr__("__call__") == null) { + if (!defaultFactory.isCallable()) { throw Py.TypeError("first argument must be callable"); } PyObject newargs[] = new PyObject[args.length - 1]; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-01 20:11:21
|
Revision: 6819 http://jython.svn.sourceforge.net/jython/?rev=6819&view=rev Author: fwierzbicki Date: 2009-10-01 20:11:08 +0000 (Thu, 01 Oct 2009) Log Message: ----------- Remove useless little inner subclasses, which where there just to add a behavior to nextToken() in Python.g -- since we override nextToken() in Python.g anyway, I relocated the functionality there. Modified Paths: -------------- trunk/jython/grammar/Python.g trunk/jython/grammar/PythonPartial.g trunk/jython/src/org/python/antlr/BaseParser.java trunk/jython/src/org/python/core/ParserFacade.java trunk/jython/tests/java/org/python/antlr/PythonPartialTester.java trunk/jython/tests/java/org/python/antlr/PythonTreeTester.java Modified: trunk/jython/grammar/Python.g =================================================================== --- trunk/jython/grammar/Python.g 2009-10-01 01:25:40 UTC (rev 6818) +++ trunk/jython/grammar/Python.g 2009-10-01 20:11:08 UTC (rev 6819) @@ -228,6 +228,7 @@ * remain). */ public Token nextToken() { + startPos = getCharPositionInLine(); while (true) { state.token = null; state.channel = Token.DEFAULT_CHANNEL; Modified: trunk/jython/grammar/PythonPartial.g =================================================================== --- trunk/jython/grammar/PythonPartial.g 2009-10-01 01:25:40 UTC (rev 6818) +++ trunk/jython/grammar/PythonPartial.g 2009-10-01 20:11:08 UTC (rev 6819) @@ -121,6 +121,7 @@ * remain). */ public Token nextToken() { + startPos = getCharPositionInLine(); while (true) { state.token = null; state.channel = Token.DEFAULT_CHANNEL; Modified: trunk/jython/src/org/python/antlr/BaseParser.java =================================================================== --- trunk/jython/src/org/python/antlr/BaseParser.java 2009-10-01 01:25:40 UTC (rev 6818) +++ trunk/jython/src/org/python/antlr/BaseParser.java 2009-10-01 20:11:08 UTC (rev 6819) @@ -31,39 +31,10 @@ this.errorHandler = eh; } - public static class PyLexer extends PythonLexer { - public PyLexer(CharStream lexer, boolean single) { - super(lexer); - this.single = single; - } - - public PyLexer(CharStream lexer) { - this(lexer, false); - } - - - @Override - public Token nextToken() { - startPos = getCharPositionInLine(); - return super.nextToken(); - } - } - - public static class PyPartialLexer extends PythonPartialLexer { - public PyPartialLexer(CharStream lexer) { - super(lexer); - } - - @Override - public Token nextToken() { - startPos = getCharPositionInLine(); - return super.nextToken(); - } - } - private PythonParser setupParser(boolean single) { - PythonLexer lexer = new PyLexer(charStream, single); + PythonLexer lexer = new PythonLexer(charStream); lexer.setErrorHandler(errorHandler); + lexer.single = single; CommonTokenStream tokens = new CommonTokenStream(lexer); PythonTokenSource indentedSource = new PythonTokenSource(tokens, filename, single); tokens = new CommonTokenStream(indentedSource); Modified: trunk/jython/src/org/python/core/ParserFacade.java =================================================================== --- trunk/jython/src/org/python/core/ParserFacade.java 2009-10-01 01:25:40 UTC (rev 6818) +++ trunk/jython/src/org/python/core/ParserFacade.java 2009-10-01 20:11:08 UTC (rev 6819) @@ -232,7 +232,7 @@ try { bufreader.reset(); CharStream cs = new NoCloseReaderStream(bufreader); - lexer = new BaseParser.PyPartialLexer(cs); + lexer = new PythonPartialLexer(cs); CommonTokenStream tokens = new CommonTokenStream(lexer); PythonTokenSource indentedSource = new PythonTokenSource(tokens, filename); tokens = new CommonTokenStream(indentedSource); Modified: trunk/jython/tests/java/org/python/antlr/PythonPartialTester.java =================================================================== --- trunk/jython/tests/java/org/python/antlr/PythonPartialTester.java 2009-10-01 01:25:40 UTC (rev 6818) +++ trunk/jython/tests/java/org/python/antlr/PythonPartialTester.java 2009-10-01 20:11:08 UTC (rev 6819) @@ -14,9 +14,8 @@ try { PythonTree result = null; CharStream input = new ANTLRFileStream(args[0]); - PythonPartialLexer lexer = new BaseParser.PyPartialLexer(input); + PythonPartialLexer lexer = new PythonPartialLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); - //PythonTokenSource indentedSource = new PythonTokenSource(tokens); PythonTokenSource indentedSource = new PythonTokenSource(tokens, "<test>"); tokens = new CommonTokenStream(indentedSource); PythonPartialParser parser = new PythonPartialParser(tokens); Modified: trunk/jython/tests/java/org/python/antlr/PythonTreeTester.java =================================================================== --- trunk/jython/tests/java/org/python/antlr/PythonTreeTester.java 2009-10-01 01:25:40 UTC (rev 6818) +++ trunk/jython/tests/java/org/python/antlr/PythonTreeTester.java 2009-10-01 20:11:08 UTC (rev 6819) @@ -30,7 +30,7 @@ //ErrorHandler eh = new ListErrorHandler(); ErrorHandler eh = new FailFastHandler(); CharStream input = new ANTLRFileStream(args[0]); - PythonLexer lexer = new BaseParser.PyLexer(input); + PythonLexer lexer = new PythonLexer(input); lexer.setErrorHandler(eh); CommonTokenStream tokens = new CommonTokenStream(lexer); PythonTokenSource indentedSource = new PythonTokenSource(tokens, args[0]); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-02 01:46:49
|
Revision: 6822 http://jython.svn.sourceforge.net/jython/?rev=6822&view=rev Author: pjenvey Date: 2009-10-02 01:46:27 +0000 (Fri, 02 Oct 2009) Log Message: ----------- allow exec of PyByteCode objects and simplify pycimport so it's not creating frames directly Modified Paths: -------------- trunk/jython/Lib/pycimport.py trunk/jython/src/org/python/core/Py.java Modified: trunk/jython/Lib/pycimport.py =================================================================== --- trunk/jython/Lib/pycimport.py 2009-10-02 00:59:40 UTC (rev 6821) +++ trunk/jython/Lib/pycimport.py 2009-10-02 01:46:27 UTC (rev 6822) @@ -1,7 +1,6 @@ -import sys +import imp import os - -from org.python.core import imp as _imp, PyFrame as _Frame, Py as _Py +import sys from marshal import Unmarshaller __debugging__ = False @@ -16,11 +15,11 @@ return magic, mtime def __makeModule(name, code, path): - module = _imp.addModule(name) - builtins = _Py.getSystemState().builtins - frame = _Frame(code, module.__dict__, module.__dict__, builtins) + module = sys.modules.get(name) + if not module: + module = sys.modules[name] = imp.new_module(name) module.__file__ = path - code.call(frame) # execute module code + exec code in module.__dict__ return module class __Importer(object): Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-10-02 00:59:40 UTC (rev 6821) +++ trunk/jython/src/org/python/core/Py.java 2009-10-02 01:46:27 UTC (rev 6822) @@ -1178,8 +1178,7 @@ return makeException(null); } - public static PyObject runCode(PyCode code, PyObject locals, - PyObject globals) { + public static PyObject runCode(PyCode code, PyObject locals, PyObject globals) { PyFrame f; ThreadState ts = getThreadState(); if (locals == null || locals == Py.None) { @@ -1194,13 +1193,12 @@ globals = ts.frame.f_globals; } - PyTableCode tc = null; - if (code instanceof PyTableCode) { - tc = (PyTableCode) code; + PyBaseCode baseCode = null; + if (code instanceof PyBaseCode) { + baseCode = (PyBaseCode) code; } - f = new PyFrame(tc, locals, globals, - Py.getSystemState().getBuiltins()); + f = new PyFrame(baseCode, locals, globals, Py.getSystemState().getBuiltins()); return code.call(ts, f); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-02 04:06:12
|
Revision: 6824 http://jython.svn.sourceforge.net/jython/?rev=6824&view=rev Author: pjenvey Date: 2009-10-02 04:05:54 +0000 (Fri, 02 Oct 2009) Log Message: ----------- o convert PyFrame to exposed annotations o specify its cached type during construction to avoid repeated PyType.fromClass calls o fix the f_lineno value while tracing PyByteCode Modified Paths: -------------- trunk/jython/CoreExposed.includes trunk/jython/src/org/python/core/PyFrame.java trunk/jython/src/org/python/core/PyTraceback.java Modified: trunk/jython/CoreExposed.includes =================================================================== --- trunk/jython/CoreExposed.includes 2009-10-02 03:45:27 UTC (rev 6823) +++ trunk/jython/CoreExposed.includes 2009-10-02 04:05:54 UTC (rev 6824) @@ -17,6 +17,7 @@ org/python/core/PyEllipsis.class org/python/core/PyFile.class org/python/core/PyFloat.class +org/python/core/PyFrame.class org/python/core/PyFrozenSet.class org/python/core/PyFunction.class org/python/core/PyGenerator.class Modified: trunk/jython/src/org/python/core/PyFrame.java =================================================================== --- trunk/jython/src/org/python/core/PyFrame.java 2009-10-02 03:45:27 UTC (rev 6823) +++ trunk/jython/src/org/python/core/PyFrame.java 2009-10-02 04:05:54 UTC (rev 6824) @@ -4,50 +4,63 @@ */ package org.python.core; +import org.python.expose.ExposedDelete; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedSet; +import org.python.expose.ExposedType; + /** * A Python frame object. */ +@ExposedType(name = "frame", isBaseType = false) public class PyFrame extends PyObject { + public static final PyType TYPE = PyType.fromClass(PyFrame.class); + /** Previous frame or null. */ + @ExposedGet public PyFrame f_back; /** The underyling code object. */ + @ExposedGet public PyBaseCode f_code; - /** Local symbol table. */ - public PyObject f_locals; + /** builtin symbol table. */ + @ExposedGet + public PyObject f_builtins; /** Global symbol table. */ + @ExposedGet public PyObject f_globals; + /** Local symbol table. */ + public PyObject f_locals; + /** Current line number. */ public int f_lineno; - /** builtin symbol table. */ - public PyObject f_builtins; - public PyObject[] f_fastlocals; /** Nested scopes: cell + free env. */ public PyCell[] f_env; + private int env_j = 0; + public int f_ncells; public int f_nfreevars; + @ExposedGet public int f_lasti; public Object[] f_savedlocals; - private int env_j = 0; - private Object generatorInput = Py.None; /** with context exits - used by generated bytecode */ public PyObject[] f_exits; - /** an interface to functions suitable for tracing, e.g. via sys.settrace(). */ + /** An interface to functions suitable for tracing, e.g. via sys.settrace(). */ public TraceFunction tracefunc; private static final String NAME_ERROR_MSG = "name '%.200s' is not defined"; @@ -57,10 +70,8 @@ private static final String UNBOUNDLOCAL_ERROR_MSG = "local variable '%.200s' referenced before assignment"; - private static final String[] __members__ = {"f_back", "f_code", "f_locals", "f_globals", - "f_lineno", "f_builtins", "f_trace"}; - public PyFrame(PyBaseCode code, PyObject locals, PyObject globals, PyObject builtins) { + super(TYPE); f_code = code; f_locals = locals; f_globals = globals; @@ -112,14 +123,6 @@ } } - public PyObject __dir__() { - PyString members[] = new PyString[__members__.length]; - for (int i = 0; i < __members__.length; i++) { - members[i] = new PyString(__members__[i]); - } - return new PyList(members); - } - void setGeneratorInput(Object value) { generatorInput = value; } @@ -134,58 +137,13 @@ return generatorInput; } - private void throwReadonly(String name) { - for (String member : __members__) { - if (member == name) { - throw Py.TypeError("readonly attribute"); - } - } - throw Py.AttributeError(name); - } - - public void __setattr__(String name, PyObject value) { - // In CPython, some of the frame's attributes are read/writeable - if (name == "f_trace") { - tracefunc = new PythonTraceFunction(value); - } else { - throwReadonly(name); - } - // not yet implemented: - // f_exc_type - // f_exc_value - // f_exc_traceback - } - - public void __delattr__(String name) { - if (name == "f_trace") { - tracefunc = null; - } else { - throwReadonly(name); - } - // not yet implemented: - // f_exc_type - // f_exc_value - // f_exc_traceback - } - - public PyObject __findattr_ex__(String name) { - if (name == "f_locals") { - return getLocals(); - } else if (name == "f_trace") { - if (tracefunc instanceof PythonTraceFunction) { - return ((PythonTraceFunction)tracefunc).tracefunc; - } - return Py.None; - } - return super.__findattr_ex__(name); - } - /** * Return the locals dict. First merges the fast locals into * f_locals, then returns the updated f_locals. * * @return a PyObject mapping of locals */ + @ExposedGet(name = "f_locals") public PyObject getLocals() { if (f_locals == null) { f_locals = new PyStringMap(); @@ -218,6 +176,22 @@ return f_locals; } + @ExposedGet(name = "f_trace") + public PyObject getTrace() { + return tracefunc instanceof PythonTraceFunction ? + ((PythonTraceFunction)tracefunc).tracefunc : Py.None; + } + + @ExposedSet(name = "f_trace") + public void setTrace(PyObject trace) { + tracefunc = new PythonTraceFunction(trace); + } + + @ExposedDelete(name = "f_trace") + public void delTrace() { + tracefunc = null; + } + /** * Return the current f_locals dict. * @@ -243,8 +217,9 @@ } } + @ExposedGet(name = "f_lineno") public int getline() { - return f_code.getline(this); + return tracefunc != null ? f_lineno : f_code.getline(this); } public PyObject getlocal(int index) { Modified: trunk/jython/src/org/python/core/PyTraceback.java =================================================================== --- trunk/jython/src/org/python/core/PyTraceback.java 2009-10-02 03:45:27 UTC (rev 6823) +++ trunk/jython/src/org/python/core/PyTraceback.java 2009-10-02 04:05:54 UTC (rev 6824) @@ -26,7 +26,7 @@ super(TYPE); tb_next = next; tb_frame = frame; - tb_lineno = frame.getline(); + tb_lineno = frame.f_code.getline(frame); } private String tracebackInfo() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-03 20:35:17
|
Revision: 6829 http://jython.svn.sourceforge.net/jython/?rev=6829&view=rev Author: pjenvey Date: 2009-10-03 20:34:59 +0000 (Sat, 03 Oct 2009) Log Message: ----------- add the ability for the method exposer to optionally pass in the current ThreadState when a method signature requests it @ arg 0 Modified Paths: -------------- trunk/jython/src/org/python/expose/generate/ClassMethodExposer.java trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java trunk/jython/src/org/python/expose/generate/MethodExposer.java trunk/jython/src/org/python/expose/generate/PyTypes.java trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java Modified: trunk/jython/src/org/python/expose/generate/ClassMethodExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ClassMethodExposer.java 2009-10-03 00:48:54 UTC (rev 6828) +++ trunk/jython/src/org/python/expose/generate/ClassMethodExposer.java 2009-10-03 20:34:59 UTC (rev 6829) @@ -29,12 +29,26 @@ private static Type[] getArgs(Type onType, String methodName, String desc) { Type[] args = Type.getArgumentTypes(desc); - if (args.length == 0 || !args[0].equals(PYTYPE)) { - throw new InvalidExposingException("The first argument to an ExposedClassMethod must be PyType[method=" - + onType.getClassName() + "." + methodName + "]"); + boolean needsThreadState = needsThreadState(args); + int offset = needsThreadState ? 1 : 0; + + if (args.length == offset || !args[offset].equals(PYTYPE)) { + String msg = String.format("ExposedClassMethod's first argument %smust be " + + "PyType[method=%s.%s]", + needsThreadState ? "(following ThreadState) " : "", + onType.getClassName(), methodName); + throw new InvalidExposingException(msg); } + + // Remove PyType from the exposed __call__'s args, it'll be already bound as self Type[] filledInArgs = new Type[args.length - 1]; - System.arraycopy(args, 1, filledInArgs, 0, filledInArgs.length); + if (needsThreadState) { + // ThreadState precedes PyType + filledInArgs[0] = args[0]; + System.arraycopy(args, 2, filledInArgs, 1, filledInArgs.length - 1); + } else { + System.arraycopy(args, 1, filledInArgs, 0, filledInArgs.length); + } return filledInArgs; } @@ -47,4 +61,13 @@ protected void checkSelf() { mv.visitTypeInsn(CHECKCAST, PYTYPE.getInternalName()); } + + @Override + protected void loadSelfAndThreadState() { + // ThreadState precedes self for ClassMethods, load it first if necessary + loadThreadState(); + // Push self on the stack so we can call it + get("self", PYOBJ); + checkSelf(); + } } Modified: trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java 2009-10-03 00:48:54 UTC (rev 6828) +++ trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java 2009-10-03 20:34:59 UTC (rev 6829) @@ -99,7 +99,7 @@ + "', not a '"); } }); - mv.visitVarInsn(ALOAD, 1); + mv.visitVarInsn(ALOAD, !needsThreadState(args) ? 1 : 2); call(PYOBJ, "getType", PYTYPE); call(PYTYPE, "fastGetName", STRING); call(STRING_BUILDER, "append", STRING_BUILDER, STRING); Modified: trunk/jython/src/org/python/expose/generate/MethodExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/MethodExposer.java 2009-10-03 00:48:54 UTC (rev 6828) +++ trunk/jython/src/org/python/expose/generate/MethodExposer.java 2009-10-03 20:34:59 UTC (rev 6829) @@ -132,14 +132,27 @@ } private void generateWideCall() { - startMethod("__call__", PYOBJ, APYOBJ, ASTRING); - get("self", PYOBJ); - checkSelf(); - mv.visitVarInsn(ALOAD, 1); - mv.visitVarInsn(ALOAD, 2); + boolean needsThreadState = needsThreadState(args); + int offset = needsThreadState ? 1 : 0; + Type[] callArgs; + + if (needsThreadState) { + callArgs = new Type[] {THREAD_STATE, APYOBJ, ASTRING}; + } else { + callArgs = new Type[] {APYOBJ, ASTRING}; + } + startMethod("__call__", PYOBJ, callArgs); + + loadSelfAndThreadState(); + mv.visitVarInsn(ALOAD, offset + 1); + mv.visitVarInsn(ALOAD, offset + 2); makeCall(); toPy(returnType); endMethod(ARETURN); + + if (needsThreadState) { + generateCallNoThreadState(callArgs); + } } private boolean hasDefault(int argIndex) { @@ -151,17 +164,25 @@ } private void generateCall(int numDefaults) { - int usedLocals = 1;// We always have one used local for self - Type[] callArgs = new Type[args.length - numDefaults]; - for(int i = 0; i < callArgs.length; i++) { + boolean needsThreadState = needsThreadState(args); + int requiredLength = args.length - numDefaults; + int offset = needsThreadState ? 1 : 0; + // We always have one used local for self, and possibly one for ThreadState + int usedLocals = 1 + offset; + Type[] callArgs = new Type[requiredLength]; + + if (needsThreadState) { + callArgs[0] = THREAD_STATE; + } + for(int i = offset; i < callArgs.length; i++) { callArgs[i] = PYOBJ; } startMethod("__call__", PYOBJ, callArgs); - // Push self on the stack so we can call it - get("self", PYOBJ); - checkSelf(); + + loadSelfAndThreadState(); // Push the passed in callArgs onto the stack, and convert them if necessary - for(int i = 0; i < callArgs.length; i++) { + int i; + for(i = offset; i < requiredLength; i++) { mv.visitVarInsn(ALOAD, usedLocals++); if(PRIMITIVES.containsKey(args[i])) { callStatic(PY, "py2" + args[i].getClassName(), args[i], PYOBJ); @@ -174,14 +195,47 @@ } } // Push the defaults onto the stack - for(int i = callArgs.length; i < args.length; i++) { + for(; i < args.length; i++) { pushDefault(getDefault(i), args[i]); } makeCall(); toPy(returnType); endMethod(ARETURN); + + if (needsThreadState) { + generateCallNoThreadState(callArgs); + } } + private void generateCallNoThreadState(Type[] callArgs) { + Type[] noThreadStateArgs = new Type[callArgs.length - 1]; + System.arraycopy(callArgs, 1, noThreadStateArgs, 0, noThreadStateArgs.length); + startMethod("__call__", PYOBJ, noThreadStateArgs); + + mv.visitVarInsn(ALOAD, 0); + callStatic(PY, "getThreadState", THREAD_STATE); + for (int i = 0; i < noThreadStateArgs.length; i++) { + mv.visitVarInsn(ALOAD, i + 1); + } + + call(thisType, "__call__", PYOBJ, callArgs); + endMethod(ARETURN); + } + + protected void loadSelfAndThreadState() { + // Push self on the stack so we can call it + get("self", PYOBJ); + checkSelf(); + // Load ThreadState if necessary + loadThreadState(); + } + + protected void loadThreadState() { + if (needsThreadState(args)) { + mv.visitVarInsn(ALOAD, 1); + } + } + protected abstract void checkSelf(); protected abstract void makeCall(); @@ -218,8 +272,14 @@ } } + protected static boolean needsThreadState(Type[] args) { + return args.length > 0 && args[0].equals(THREAD_STATE); + } + protected static boolean isWide(Type[] args) { - return args.length == 2 && args[0].equals(APYOBJ) && args[1].equals(ASTRING); + int offset = needsThreadState(args) ? 1 : 0; + return args.length == 2 + offset + && args[offset].equals(APYOBJ) && args[offset + 1].equals(ASTRING); } } Modified: trunk/jython/src/org/python/expose/generate/PyTypes.java =================================================================== --- trunk/jython/src/org/python/expose/generate/PyTypes.java 2009-10-03 00:48:54 UTC (rev 6828) +++ trunk/jython/src/org/python/expose/generate/PyTypes.java 2009-10-03 20:34:59 UTC (rev 6829) @@ -15,6 +15,7 @@ import org.python.core.PyObject; import org.python.core.PyString; import org.python.core.PyType; +import org.python.core.ThreadState; import org.python.expose.ExposeAsSuperclass; import org.python.expose.ExposedClassMethod; import org.python.expose.ExposedDelete; @@ -71,6 +72,8 @@ public static final Type BUILTIN_INFO = Type.getType(PyBuiltinCallable.Info.class); + public static final Type THREAD_STATE = Type.getType(ThreadState.class); + // Exposer Jython types public static final Type EXPOSED_TYPE = Type.getType(ExposedType.class); Modified: trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java 2009-10-03 00:48:54 UTC (rev 6828) +++ trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java 2009-10-03 20:34:59 UTC (rev 6829) @@ -16,7 +16,7 @@ .getResourceAsStream("org/python/expose/generate/SimpleExposed.class"); ExposedTypeProcessor ice = new ExposedTypeProcessor(in); assertEquals("simpleexposed", ice.getName()); - assertEquals(19, ice.getMethodExposers().size()); + assertEquals(22, ice.getMethodExposers().size()); assertNotNull(ice.getNewExposer()); assertEquals(1, ice.getDescriptorExposers().size()); assertEquals("simpleexposed", ice.getTypeExposer().getName()); Modified: trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java 2009-10-03 00:48:54 UTC (rev 6828) +++ trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java 2009-10-03 20:34:59 UTC (rev 6829) @@ -6,6 +6,8 @@ import org.python.core.Py; import org.python.core.PyBuiltinCallable; import org.python.core.PyException; +import org.python.core.PyObject; +import org.python.core.ThreadState; import org.python.expose.MethodType; public class MethodExposerTest extends InterpTestCase implements Opcodes, PyTypes { @@ -226,6 +228,55 @@ assertEquals(3, bound.__call__(Py.newString("nothello"), Py.One).asInt()); } + public void testThreadState() throws Exception { + PyBuiltinCallable bound = createBound("needsThreadState", STRING, THREAD_STATE, STRING); + ThreadState ts = Py.getThreadState(); + PyObject expected = Py.newString("foo got state " + ts.hashCode()); + assertEquals(expected, bound.__call__(Py.getThreadState(), Py.newString("foo"))); + assertEquals(expected, bound.__call__(Py.newString("foo"))); + ts = new ThreadState(new Thread(), ts.systemState); + assertEquals(Py.newString("foo got state " + ts.hashCode()), + bound.__call__(ts, Py.newString("foo"))); + } + + public void testThreadStateFullArguments() throws Exception { + InstanceMethodExposer exp = new InstanceMethodExposer(Type.getType(SimpleExposed.class), + Opcodes.ACC_PUBLIC, + "needsThreadStateWide", + Type.getMethodDescriptor(Type.INT_TYPE, + new Type[] {THREAD_STATE, + APYOBJ, + ASTRING}), + "simpleexposed"); + PyBuiltinCallable bound = createBound(exp); + assertEquals(Py.Zero, bound.__call__(Py.getThreadState())); + assertEquals(Py.Zero, bound.__call__()); + assertEquals(Py.One, bound.__call__(Py.getThreadState(), Py.One)); + assertEquals(Py.One, bound.__call__(Py.One)); + } + + public void testThreadStateClassMethod() throws Exception { + ClassMethodExposer exp = new ClassMethodExposer(Type.getType(SimpleExposed.class), + Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, + "needsThreadStateClass", + Type.getMethodDescriptor(STRING, + new Type[] {THREAD_STATE, + PYTYPE, + STRING, + STRING}), + "simpleexposed", + new String[0], + new String[] {"null"}, + ""); + PyBuiltinCallable bound = createBound(exp); + ThreadState ts = Py.getThreadState(); + PyObject arg0 = Py.newString("bar"); + PyObject arg1 = Py.newString(" and extra"); + PyObject expected = Py.newString("bar got state " + ts.hashCode() + " got type and extra"); + assertEquals(expected, bound.__call__(Py.getThreadState(), arg0, arg1)); + assertEquals(expected, bound.__call__(arg0, arg1)); + } + public void test__new__() throws Exception { try { createExposer("__new__", VOID); Modified: trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java 2009-10-03 00:48:54 UTC (rev 6828) +++ trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java 2009-10-03 20:34:59 UTC (rev 6829) @@ -6,6 +6,7 @@ import org.python.core.PyObject; import org.python.core.PyString; import org.python.core.PyType; +import org.python.core.ThreadState; import org.python.expose.ExposedClassMethod; import org.python.expose.ExposedDelete; import org.python.expose.ExposedGet; @@ -150,4 +151,32 @@ public String toStringVal = TO_STRING_RETURN; public static final String TO_STRING_RETURN = "A simple test class"; + + @ExposedMethod + public String needsThreadState(ThreadState state, String s) { + return needsThreadStateClass(state, null, s, null); + } + + @ExposedMethod + public int needsThreadStateWide(ThreadState state, PyObject[] args, String[] kws) { + if (state == null) { + return -1; + } + return args.length + kws.length; + } + + @ExposedClassMethod(defaults = {"null"}) + public static String needsThreadStateClass(ThreadState state, PyType onType, String s, + String possiblyNull) { + if (state != null) { + s += " got state " + state.hashCode(); + } + if (onType != null) { + s += " got type"; + } + if (possiblyNull != null) { + s += possiblyNull; + } + return s; + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |