You can subscribe to this list here.
2000 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(1) |
Nov
(107) |
Dec
(67) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2001 |
Jan
(76) |
Feb
(125) |
Mar
(72) |
Apr
(13) |
May
(18) |
Jun
(12) |
Jul
(129) |
Aug
(47) |
Sep
(1) |
Oct
(36) |
Nov
(128) |
Dec
(124) |
2002 |
Jan
(59) |
Feb
|
Mar
(14) |
Apr
(14) |
May
(72) |
Jun
(9) |
Jul
(3) |
Aug
(5) |
Sep
(18) |
Oct
(65) |
Nov
(28) |
Dec
(12) |
2003 |
Jan
(10) |
Feb
(2) |
Mar
(4) |
Apr
(33) |
May
(21) |
Jun
(9) |
Jul
(29) |
Aug
(34) |
Sep
(4) |
Oct
(8) |
Nov
(15) |
Dec
(4) |
2004 |
Jan
(26) |
Feb
(12) |
Mar
(11) |
Apr
(9) |
May
(7) |
Jun
|
Jul
(5) |
Aug
|
Sep
(3) |
Oct
(7) |
Nov
(1) |
Dec
(10) |
2005 |
Jan
(2) |
Feb
(72) |
Mar
(16) |
Apr
(39) |
May
(48) |
Jun
(97) |
Jul
(57) |
Aug
(13) |
Sep
(16) |
Oct
(24) |
Nov
(100) |
Dec
(24) |
2006 |
Jan
(15) |
Feb
(34) |
Mar
(33) |
Apr
(31) |
May
(79) |
Jun
(64) |
Jul
(41) |
Aug
(64) |
Sep
(31) |
Oct
(46) |
Nov
(55) |
Dec
(37) |
2007 |
Jan
(32) |
Feb
(61) |
Mar
(11) |
Apr
(58) |
May
(46) |
Jun
(30) |
Jul
(94) |
Aug
(93) |
Sep
(86) |
Oct
(69) |
Nov
(125) |
Dec
(177) |
2008 |
Jan
(169) |
Feb
(97) |
Mar
(74) |
Apr
(113) |
May
(120) |
Jun
(334) |
Jul
(215) |
Aug
(237) |
Sep
(72) |
Oct
(189) |
Nov
(126) |
Dec
(160) |
2009 |
Jan
(180) |
Feb
(45) |
Mar
(98) |
Apr
(140) |
May
(151) |
Jun
(71) |
Jul
(107) |
Aug
(119) |
Sep
(73) |
Oct
(121) |
Nov
(14) |
Dec
(6) |
2010 |
Jan
(13) |
Feb
(9) |
Mar
(10) |
Apr
(64) |
May
(3) |
Jun
(16) |
Jul
(7) |
Aug
(23) |
Sep
(17) |
Oct
(37) |
Nov
(5) |
Dec
(8) |
2011 |
Jan
(10) |
Feb
(11) |
Mar
(77) |
Apr
(11) |
May
(2) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <fwi...@us...> - 2008-12-02 03:31:51
|
Revision: 5672 http://jython.svn.sourceforge.net/jython/?rev=5672&view=rev Author: fwierzbicki Date: 2008-12-02 03:31:45 +0000 (Tue, 02 Dec 2008) Log Message: ----------- Finally some real progress on PyObject backed ast nodes. Reverted back to 2.5 style test_ast.py as a middle step on the way to 2.6 style test_ast.py. Modified Paths: -------------- branches/astwrite/Lib/test/test_ast.py branches/astwrite/ast/asdl_antlr.py branches/astwrite/grammar/Python.g branches/astwrite/src/org/python/antlr/adapter/AliasAdapter.java branches/astwrite/src/org/python/antlr/adapter/AstAdapter.java branches/astwrite/src/org/python/antlr/adapter/AstAdapters.java branches/astwrite/src/org/python/antlr/adapter/CmpopAdapter.java branches/astwrite/src/org/python/antlr/adapter/ComprehensionAdapter.java branches/astwrite/src/org/python/antlr/adapter/ExcepthandlerAdapter.java branches/astwrite/src/org/python/antlr/adapter/ExprAdapter.java branches/astwrite/src/org/python/antlr/adapter/IdentifierAdapter.java branches/astwrite/src/org/python/antlr/adapter/KeywordAdapter.java branches/astwrite/src/org/python/antlr/adapter/SliceAdapter.java branches/astwrite/src/org/python/antlr/adapter/StmtAdapter.java branches/astwrite/src/org/python/antlr/ast/Assert.java branches/astwrite/src/org/python/antlr/ast/Assign.java branches/astwrite/src/org/python/antlr/ast/AstModule.java branches/astwrite/src/org/python/antlr/ast/Attribute.java branches/astwrite/src/org/python/antlr/ast/AugAssign.java branches/astwrite/src/org/python/antlr/ast/BinOp.java branches/astwrite/src/org/python/antlr/ast/BoolOp.java branches/astwrite/src/org/python/antlr/ast/Break.java branches/astwrite/src/org/python/antlr/ast/Call.java branches/astwrite/src/org/python/antlr/ast/ClassDef.java branches/astwrite/src/org/python/antlr/ast/Compare.java branches/astwrite/src/org/python/antlr/ast/Continue.java branches/astwrite/src/org/python/antlr/ast/Delete.java branches/astwrite/src/org/python/antlr/ast/Dict.java branches/astwrite/src/org/python/antlr/ast/Ellipsis.java branches/astwrite/src/org/python/antlr/ast/ExceptHandler.java branches/astwrite/src/org/python/antlr/ast/Exec.java branches/astwrite/src/org/python/antlr/ast/Expr.java branches/astwrite/src/org/python/antlr/ast/Expression.java branches/astwrite/src/org/python/antlr/ast/ExtSlice.java branches/astwrite/src/org/python/antlr/ast/For.java branches/astwrite/src/org/python/antlr/ast/FunctionDef.java branches/astwrite/src/org/python/antlr/ast/GeneratorExp.java branches/astwrite/src/org/python/antlr/ast/Global.java branches/astwrite/src/org/python/antlr/ast/If.java branches/astwrite/src/org/python/antlr/ast/IfExp.java branches/astwrite/src/org/python/antlr/ast/Import.java branches/astwrite/src/org/python/antlr/ast/ImportFrom.java branches/astwrite/src/org/python/antlr/ast/Index.java branches/astwrite/src/org/python/antlr/ast/Interactive.java branches/astwrite/src/org/python/antlr/ast/Lambda.java branches/astwrite/src/org/python/antlr/ast/List.java branches/astwrite/src/org/python/antlr/ast/ListComp.java branches/astwrite/src/org/python/antlr/ast/Module.java branches/astwrite/src/org/python/antlr/ast/Name.java branches/astwrite/src/org/python/antlr/ast/Num.java branches/astwrite/src/org/python/antlr/ast/Pass.java branches/astwrite/src/org/python/antlr/ast/Print.java branches/astwrite/src/org/python/antlr/ast/Raise.java branches/astwrite/src/org/python/antlr/ast/Repr.java branches/astwrite/src/org/python/antlr/ast/Return.java branches/astwrite/src/org/python/antlr/ast/Slice.java branches/astwrite/src/org/python/antlr/ast/Str.java branches/astwrite/src/org/python/antlr/ast/Subscript.java branches/astwrite/src/org/python/antlr/ast/Suite.java branches/astwrite/src/org/python/antlr/ast/TryExcept.java branches/astwrite/src/org/python/antlr/ast/TryFinally.java branches/astwrite/src/org/python/antlr/ast/Tuple.java branches/astwrite/src/org/python/antlr/ast/UnaryOp.java branches/astwrite/src/org/python/antlr/ast/VisitorBase.java branches/astwrite/src/org/python/antlr/ast/While.java branches/astwrite/src/org/python/antlr/ast/With.java branches/astwrite/src/org/python/antlr/ast/Yield.java branches/astwrite/src/org/python/antlr/ast/aliasType.java branches/astwrite/src/org/python/antlr/ast/argumentsType.java branches/astwrite/src/org/python/antlr/ast/cmpopType.java branches/astwrite/src/org/python/antlr/ast/comprehensionType.java branches/astwrite/src/org/python/antlr/ast/excepthandlerType.java branches/astwrite/src/org/python/antlr/ast/exprType.java branches/astwrite/src/org/python/antlr/ast/keywordType.java branches/astwrite/src/org/python/antlr/ast/modType.java branches/astwrite/src/org/python/antlr/ast/sliceType.java branches/astwrite/src/org/python/antlr/ast/stmtType.java Added Paths: ----------- branches/astwrite/src/org/python/core/AstList.java Removed Paths: ------------- branches/astwrite/src/org/python/antlr/adapter/ListWrapper.java Modified: branches/astwrite/Lib/test/test_ast.py =================================================================== --- branches/astwrite/Lib/test/test_ast.py 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/Lib/test/test_ast.py 2008-12-02 03:31:45 UTC (rev 5672) @@ -1,49 +1,36 @@ -import sys, itertools, unittest -from test import test_support +#Taken and modified from CPython's release25-maint branch, revision 62446. +import sys,os, itertools import ast -if sys.platform.startswith('java'): - import java.util.List - - ast_list = java.util.List - get_symbol_key = lambda op: op - - def get_class_name(t): - result = t.__class__.__name__ +def get_class_name(t): + result = t.__class__.__name__ + if os.name.startswith('java'): if result in ("expr_contextType", - "boolopType", - "unaryopType", - "cmpopType", - "operatorType"): - result = str(t) - if result == "AugLoad": - result = "Load" - elif result == "AugStore": - result = "Store" - elif result.endswith("Type"): - result = result[:-4] - return result + "boolopType", + "unaryopType", + "cmpopType", + "operatorType"): + result = t.name() + else: + result = result.split(".")[-1] + if result.endswith("Type"): + result = result[:-4] + return result -else: - ast_list = list - get_symbol_key = type - get_class_name = lambda node: node.__class__.__name__ - def to_tuple(t): if t is None or isinstance(t, (basestring, int, long, complex)): return t - elif isinstance(t, ast_list): + elif hasattr(t, '__iter__'): return [to_tuple(e) for e in t] result = [get_class_name(t)] if hasattr(t, 'lineno') and hasattr(t, 'col_offset'): result.append((t.lineno, t.col_offset)) - if t._fields is None: + if not hasattr(t, '_fields') or t._fields is None: return tuple(result) for f in t._fields: result.append(to_tuple(getattr(t, f))) return tuple(result) - # These tests are compiled through "exec" # There should be atleast one test per statement exec_tests = [ @@ -147,189 +134,59 @@ # TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension # excepthandler, arguments, keywords, alias -class AST_Tests(unittest.TestCase): +if __name__=='__main__' and sys.argv[1:] == ['-g']: + for statements, kind in ((exec_tests, "exec"), (single_tests, "single"), + (eval_tests, "eval")): + print kind+"_results = [" + for s in statements: + print repr(to_tuple(compile(s, "?", kind, 0x400)))+"," + print "]" + print "run_tests()" + raise SystemExit - def _assert_order(self, ast_node, parent_pos): - if not isinstance(ast_node, ast.AST) or ast_node._fields is None: +def test_order(ast_node, parent_pos): + + if (not isinstance(ast_node, ast.AST) + or not hasattr(ast_node, '_fields') + or ast_node._fields == None): return - if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)): - node_pos = (ast_node.lineno, ast_node.col_offset) - self.assert_(node_pos >= parent_pos) - parent_pos = (ast_node.lineno, ast_node.col_offset) - for name in ast_node._fields: - value = getattr(ast_node, name) - if isinstance(value, ast_list): - for child in value: - self._assert_order(child, parent_pos) - elif value is not None: - self._assert_order(value, parent_pos) + if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)): + node_pos = (ast_node.lineno, ast_node.col_offset) + assert node_pos >= parent_pos, (node_pos, parent_pos) + parent_pos = (ast_node.lineno, ast_node.col_offset) + for name in ast_node._fields: + value = getattr(ast_node, name) + if hasattr(value, '__iter__'): + for child in value: + test_order(child, parent_pos) + elif value != None: + test_order(value, parent_pos) - def test_snippets(self): - for input, output, kind in ((exec_tests, exec_results, "exec"), - (single_tests, single_results, "single"), - (eval_tests, eval_results, "eval")): - for i, o in itertools.izip(input, output): - ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST) - self.assertEquals(to_tuple(ast_tree), o) - self._assert_order(ast_tree, (0, 0)) +def run_tests(): + for input, output, kind in ((exec_tests, exec_results, "exec"), + (single_tests, single_results, "single"), + (eval_tests, eval_results, "eval")): + for i, o in itertools.izip(input, output): + ast_tree = compile(i, "?", kind, 0x400) + assert to_tuple(ast_tree) == o, "expected %s, got %s" % ( + o, to_tuple(ast_tree)) + test_order(ast_tree, (0, 0)) - def test_nodeclasses(self): - x = ast.BinOp(1, ast.Add, 3, lineno=0) - self.assertEquals(x.left.n, 1) - self.assertEquals(x.op, ast.Add) - self.assertEquals(x.right.n, 3) - self.assertEquals(x.lineno, 0) - - # node raises exception when not given enough arguments - self.assertRaises(TypeError, ast.BinOp, 1, 2) - - # can set attributes through kwargs too - x = ast.BinOp(left=1, op=ast.Add, right=3, lineno=0) - self.assertEquals(x.left.n, 1) - self.assertEquals(x.op, ast.Add) - self.assertEquals(x.right.n, 3) - self.assertEquals(x.lineno, 0) - - # this used to fail because Sub._fields was None - x = ast.Sub() - - def test_pickling(self): - import pickle - mods = [pickle] - try: - import cPickle - mods.append(cPickle) - except ImportError: - pass - protocols = [0, 1, 2] - for mod in mods: - for protocol in protocols: - for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests): - ast2 = mod.loads(mod.dumps(ast, protocol)) - self.assertEquals(to_tuple(ast2), to_tuple(ast)) - - -class ASTHelpers_Test(unittest.TestCase): - - def test_parse(self): - a = ast.parse('foo(1 + 1)') - b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST) - self.assertEqual(ast.dump(a), ast.dump(b)) - - def test_dump(self): - node = ast.parse('spam(eggs, "and cheese")') - self.assertEqual(ast.dump(node), - u"Module(body=[Expr(value=Call(func=Name(id=u'spam', ctx=Load()), " - "args=[Name(id=u'eggs', ctx=Load()), Str(s='and cheese')], " - "keywords=[], starargs=None, kwargs=None))])" - ) - self.assertEqual(ast.dump(node, annotate_fields=False), - "Module([Expr(Call(Name(u'spam', Load()), [Name(u'eggs', Load()), " - "Str('and cheese')], [], None, None))])" - ) - self.assertEqual(ast.dump(node, include_attributes=True), - "Module(body=[Expr(value=Call(func=Name(id=u'spam', ctx=Load(), " - "lineno=1, col_offset=0), args=[Name(id=u'eggs', ctx=Load(), " - "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, " - "col_offset=11)], keywords=[], starargs=None, kwargs=None, " - "lineno=1, col_offset=0), lineno=1, col_offset=0)])" - ) - - def test_copy_location(self): - src = ast.parse('1 + 1', mode='eval') - src.body.right = ast.copy_location(ast.Num(2), src.body.right) - self.assertEqual(ast.dump(src, include_attributes=True), - 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), ' - 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, ' - 'col_offset=0))' - ) - - def test_fix_missing_locations(self): - src = ast.parse('write("spam")') - src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()), - [ast.Str('eggs')], [], None, None))) - self.assertEqual(src, ast.fix_missing_locations(src)) - self.assertEqual(ast.dump(src, include_attributes=True), - u"Module(body=[Expr(value=Call(func=Name(id=u'write', ctx=Load(), " - "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, " - "col_offset=6)], keywords=[], starargs=None, kwargs=None, " - "lineno=1, col_offset=0), lineno=1, col_offset=0), " - "Expr(value=Call(func=Name(id=u'spam', ctx=Load(), lineno=1, " - "col_offset=0), args=[Str(s=u'eggs', lineno=1, col_offset=0)], " - "keywords=[], starargs=None, kwargs=None, lineno=1, " - "col_offset=0), lineno=1, col_offset=0)])" - ) - - def test_increment_lineno(self): - src = ast.parse('1 + 1', mode='eval') - self.assertEqual(ast.increment_lineno(src, n=3), src) - self.assertEqual(ast.dump(src, include_attributes=True), - 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), ' - 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, ' - 'col_offset=0))' - ) - - def test_iter_fields(self): - node = ast.parse('foo()', mode='eval') - d = dict(ast.iter_fields(node.body)) - self.assertEqual(d.pop('func').id, 'foo') - self.assertEqual(d, {'keywords': [], 'kwargs': None, - 'args': [], 'starargs': None}) - - def test_iter_child_nodes(self): - node = ast.parse("spam(23, 42, eggs='leek')", mode='eval') - self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4) - iterator = ast.iter_child_nodes(node.body) - self.assertEqual(iterator.next().id, 'spam') - self.assertEqual(iterator.next().n, 23) - self.assertEqual(iterator.next().n, 42) - self.assertEqual(ast.dump(iterator.next()), - u"keyword(arg=u'eggs', value=Str(s='leek'))" - ) - - def test_get_docstring(self): - node = ast.parse('def foo():\n """line one\n line two"""') - self.assertEqual(ast.get_docstring(node.body[0]), - 'line one\nline two') - - def test_literal_eval(self): - self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3]) - self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42}) - self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None)) - self.assertRaises(ValueError, ast.literal_eval, 'foo()') - - -def test_main(): - test_support.run_unittest(AST_Tests, ASTHelpers_Test) - -def main(): - if __name__ != '__main__': - return - if sys.argv[1:] == ['-g']: - for statements, kind in ((exec_tests, "exec"), (single_tests, "single"), - (eval_tests, "eval")): - print kind+"_results = [" - for s in statements: - print repr(to_tuple(compile(s, "?", kind, 0x400)))+"," - print "]" - print "main()" - raise SystemExit - test_main() - +# XXX: AugStore added for Jython. Short term it is too hard to emit just "Store" as CPython does. #### EVERYTHING BELOW IS GENERATED ##### exec_results = [ ('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, []), [('Pass', (1, 9))], [])]), -('Module', [('ClassDef', (1, 0), 'C', [], [('Pass', (1, 8))], [])]), +('Module', [('ClassDef', (1, 0), 'C', [], [('Pass', (1, 8))],[])]), ('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, []), [('Return', (1, 8), ('Num', (1, 15), 1))], [])]), ('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]), ('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]), -('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Num', (1, 5), 1))]), +('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('AugStore',)), ('Add',), ('Num', (1, 5), 1))]), ('Module', [('Print', (1, 0), ('Name', (1, 8), 'f', ('Load',)), [('Num', (1, 11), 1)], False)]), ('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]), ('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]), ('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]), ('Module', [('Raise', (1, 0), ('Name', (1, 6), 'Exception', ('Load',)), ('Str', (1, 17), 'string'), None)]), -('Module', [('TryExcept', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [])]), +('Module', [('TryExcept', (1, 0), [('Pass', (2, 2))], [('excepthandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))], 3, 0)], [])]), ('Module', [('TryFinally', (1, 0), [('Pass', (2, 2))], [('Pass', (4, 2))])]), ('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]), ('Module', [('Import', (1, 0), [('alias', 'sys', None)])]), @@ -364,4 +221,4 @@ ('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))), ('Expression', ('Call', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',)), 'd', ('Load',)), [('Subscript', (1, 8), ('Attribute', (1, 8), ('Name', (1, 8), 'a', ('Load',)), 'b', ('Load',)), ('Slice', ('Num', (1, 12), 1), ('Num', (1, 14), 2), None), ('Load',))], [], None, None)), ] -main() +run_tests() Modified: branches/astwrite/ast/asdl_antlr.py =================================================================== --- branches/astwrite/ast/asdl_antlr.py 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/ast/asdl_antlr.py 2008-12-02 03:31:45 UTC (rev 5672) @@ -56,13 +56,14 @@ print >> self.file, "// Autogenerated AST node" print >> self.file, 'package org.python.antlr.ast;' if refersToPythonTree: + print >> self.file, 'import org.antlr.runtime.CommonToken;' + print >> self.file, 'import org.antlr.runtime.Token;' print >> self.file, 'import org.python.antlr.PythonTree;' print >> self.file, 'import org.python.antlr.adapter.AstAdapters;' - print >> self.file, 'import org.python.antlr.adapter.ListWrapper;' - print >> self.file, 'import org.antlr.runtime.CommonToken;' - print >> self.file, 'import org.antlr.runtime.Token;' + print >> self.file, 'import org.python.core.AstList;' print >> self.file, 'import org.python.core.Py;' print >> self.file, 'import org.python.core.PyObject;' + print >> self.file, 'import org.python.core.PyString;' print >> self.file, 'import org.python.core.PyType;' print >> self.file, 'import org.python.expose.ExposedGet;' print >> self.file, 'import org.python.expose.ExposedMethod;' @@ -201,6 +202,7 @@ self.emit("public abstract class %(name)sType extends PythonTree {" % locals(), depth) self.emit("", 0) + self.emit("public static final PyType TYPE = PyType.fromClass(%sType.class);" % name, depth + 1); self.attributes(sum, depth); @@ -405,7 +407,7 @@ self.emit("@ExposedMethod", depth) self.emit("public void Module___init__(PyObject[] args, String[] keywords) {}", depth) - fpargs = ", ".join(["Object %s" % f.name for f in fields]) + fpargs = ", ".join(["PyObject %s" % f.name for f in fields]) self.emit("public %s(%s) {" % (ctorname, fpargs), depth) for f in fields: self.emit("set%s(%s);" % (str(f.name).capitalize(), @@ -450,16 +452,26 @@ self.emit('@ExposedGet(name = "%s")' % field.name, depth) self.emit("public PyObject get%s() {" % (str(field.name).capitalize()), depth) if field.seq: - #FIXME: temporary - #self.emit("return new ListWrapper(%s, AstAdapters.%sAdapter);" % (field.name, field.type), depth+1) - self.emit("return Py.None;", depth+1) + self.emit("return new AstList(%s, AstAdapters.%sAdapter);" % (field.name, field.type), depth+1) else: - #FIXME: temporary - #self.emit("return %s;" % field.name, depth+1) - self.emit("return Py.None;", depth+1) + if str(field.type) == 'identifier': + self.emit("if (%s == null) return Py.None;" % field.name, depth+1) + self.emit("return new PyString(%s);" % field.name, depth+1) + elif str(field.type) == 'string' or str(field.type) == 'object': + self.emit("return (PyObject)%s;" % field.name, depth+1) + elif str(field.type) == 'bool': + self.emit("if (%s) return Py.True;" % field.name, depth+1) + self.emit("return Py.False;" % field.name, depth+1) + elif str(field.type) == 'int': + self.emit("return Py.newInteger(%s);" % field.name, depth+1) + elif field.typedef.simple: + self.emit("return Py.None;//(%s);" % field.name, depth+1) + else: + self.emit("return %s;" % field.name, depth+1) + #self.emit("return Py.None;", depth+1) self.emit("}", depth) self.emit('@ExposedSet(name = "%s")' % field.name, depth) - self.emit("public void set%s(Object %s) {" % (str(field.name).capitalize(), + self.emit("public void set%s(PyObject %s) {" % (str(field.name).capitalize(), field.name), depth) if field.seq: #self.emit("this.%s = new %s(" % (field.name, self.javaType(field)), depth+1) Modified: branches/astwrite/grammar/Python.g =================================================================== --- branches/astwrite/grammar/Python.g 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/grammar/Python.g 2008-12-02 03:31:45 UTC (rev 5672) @@ -145,6 +145,7 @@ import org.python.antlr.ast.With; import org.python.antlr.ast.Yield; import org.python.core.Py; +import org.python.core.PyObject; import org.python.core.PyString; import org.python.core.PyUnicode; @@ -1189,16 +1190,16 @@ } if (o instanceof Call) { Call c = (Call)o; - c.setFunc($etype); + c.setFunc((PyObject)$etype); $etype = c; } else if (o instanceof Subscript) { Subscript c = (Subscript)o; - c.setValue($etype); + c.setValue((PyObject)$etype); $etype = c; } else if (o instanceof Attribute) { Attribute c = (Attribute)o; c.setCharStartIndex($etype.getCharStartIndex()); - c.setValue($etype); + c.setValue((PyObject)$etype); $etype = c; } } Modified: branches/astwrite/src/org/python/antlr/adapter/AliasAdapter.java =================================================================== --- branches/astwrite/src/org/python/antlr/adapter/AliasAdapter.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/adapter/AliasAdapter.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -1,6 +1,7 @@ package org.python.antlr.adapter; import org.python.core.Py; +import org.python.core.PyObject; import org.python.core.PyJavaInstance; import org.python.antlr.ast.aliasType; @@ -10,13 +11,10 @@ public class AliasAdapter implements AstAdapter { - public Object adapt(Object o) { + public Object py2ast(PyObject o) { if (o == null) { return o; } - if (o instanceof PyJavaInstance) { - o = ((PyJavaInstance)o).__tojava__(aliasType.class); - } if (o instanceof aliasType) { return o; } @@ -24,10 +22,14 @@ throw Py.TypeError("Can't convert " + o.getClass().getName() + " to alias node"); } - public Object adaptIter(Object iter) { + public PyObject ast2py(Object o) { + return (PyObject)o; + } + + public List iter2ast(PyObject iter) { List<aliasType> aliases = new ArrayList<aliasType>(); for(Object o : (Iterable)iter) { - aliases.add((aliasType)adapt(o)); + aliases.add((aliasType)py2ast((PyObject)(PyObject)o)); } return aliases; } Modified: branches/astwrite/src/org/python/antlr/adapter/AstAdapter.java =================================================================== --- branches/astwrite/src/org/python/antlr/adapter/AstAdapter.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/adapter/AstAdapter.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -1,13 +1,15 @@ package org.python.antlr.adapter; +import org.python.core.PyObject; + +import java.util.List; /** * AstAdapters turn Objects into Ast nodes. */ public interface AstAdapter { - /** - * @return Ast node version of o. - */ - public abstract Object adapt(Object o); + PyObject ast2py(Object o); + Object py2ast(PyObject o); + List iter2ast(PyObject o); } Modified: branches/astwrite/src/org/python/antlr/adapter/AstAdapters.java =================================================================== --- branches/astwrite/src/org/python/antlr/adapter/AstAdapters.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/adapter/AstAdapters.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -18,44 +18,44 @@ public static SliceAdapter sliceAdapter = new SliceAdapter(); public static StmtAdapter stmtAdapter = new StmtAdapter(); - public static java.util.List<aliasType> to_aliasList(Object o) { - return (java.util.List<aliasType>)aliasAdapter.adaptIter(o); + public static java.util.List<aliasType> to_aliasList(PyObject o) { + return (java.util.List<aliasType>)aliasAdapter.iter2ast(o); } - public static java.util.List<cmpopType> to_cmpopList(Object o) { - return (java.util.List<cmpopType>)cmpopAdapter.adaptIter(o); + public static java.util.List<cmpopType> to_cmpopList(PyObject o) { + return (java.util.List<cmpopType>)cmpopAdapter.iter2ast(o); } - public static java.util.List<comprehensionType> to_comprehensionList(Object o) { - return (java.util.List<comprehensionType>)comprehensionAdapter.adaptIter(o); + public static java.util.List<comprehensionType> to_comprehensionList(PyObject o) { + return (java.util.List<comprehensionType>)comprehensionAdapter.iter2ast(o); } - public static java.util.List<excepthandlerType> to_excepthandlerList(Object o) { - return (java.util.List<excepthandlerType>)excepthandlerAdapter.adaptIter(o); + public static java.util.List<excepthandlerType> to_excepthandlerList(PyObject o) { + return (java.util.List<excepthandlerType>)excepthandlerAdapter.iter2ast(o); } - public static java.util.List<exprType> to_exprList(Object o) { - return (java.util.List<exprType>)exprAdapter.adaptIter(o); + public static java.util.List<exprType> to_exprList(PyObject o) { + return (java.util.List<exprType>)exprAdapter.iter2ast(o); } - public static java.util.List<String> to_identifierList(Object o) { - return (java.util.List<String>)identifierAdapter.adaptIter(o); + public static java.util.List<String> to_identifierList(PyObject o) { + return (java.util.List<String>)identifierAdapter.iter2ast(o); } - public static java.util.List<keywordType> to_keywordList(Object o) { - return (java.util.List<keywordType>)keywordAdapter.adaptIter(o); + public static java.util.List<keywordType> to_keywordList(PyObject o) { + return (java.util.List<keywordType>)keywordAdapter.iter2ast(o); } - public static java.util.List<sliceType> to_sliceList(Object o) { - return (java.util.List<sliceType>)sliceAdapter.adaptIter(o); + public static java.util.List<sliceType> to_sliceList(PyObject o) { + return (java.util.List<sliceType>)sliceAdapter.iter2ast(o); } - public static java.util.List<stmtType> to_stmtList(Object o) { - return (java.util.List<stmtType>)stmtAdapter.adaptIter(o); + public static java.util.List<stmtType> to_stmtList(PyObject o) { + return (java.util.List<stmtType>)stmtAdapter.iter2ast(o); } - public static exprType to_expr(Object o) { - return (exprType)exprAdapter.adapt(o); + public static exprType to_expr(PyObject o) { + return (exprType)exprAdapter.py2ast(o); } public static int to_int(Object o) { @@ -66,8 +66,8 @@ throw Py.TypeError("Can't convert " + o.getClass().getName() + " to int node"); } - public static String to_identifier(Object o) { - return (String)identifierAdapter.adapt(o); + public static String to_identifier(PyObject o) { + return (String)identifierAdapter.py2ast(o); } public static expr_contextType to_expr_context(Object o) { @@ -78,12 +78,12 @@ throw Py.TypeError("Can't convert " + o.getClass().getName() + " to expr_context node"); } - public static sliceType to_slice(Object o) { - return (sliceType)sliceAdapter.adapt(o); + public static sliceType to_slice(PyObject o) { + return (sliceType)sliceAdapter.py2ast(o); } - public static stmtType to_stmt(Object o) { - return (stmtType)stmtAdapter.adapt(o); + public static stmtType to_stmt(PyObject o) { + return (stmtType)stmtAdapter.py2ast(o); } public static String to_string(Object o) { Modified: branches/astwrite/src/org/python/antlr/adapter/CmpopAdapter.java =================================================================== --- branches/astwrite/src/org/python/antlr/adapter/CmpopAdapter.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/adapter/CmpopAdapter.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -1,6 +1,7 @@ package org.python.antlr.adapter; import org.python.core.Py; +import org.python.core.PyObject; import org.python.core.PyJavaInstance; import org.python.antlr.ast.cmpopType; @@ -10,24 +11,23 @@ public class CmpopAdapter implements AstAdapter { - public Object adapt(Object o) { + public Object py2ast(PyObject o) { if (o == null) { return o; } - if (o instanceof PyJavaInstance) { - o = ((PyJavaInstance)o).__tojava__(cmpopType.class); - } - if (o instanceof cmpopType) { - return o; - } + return o; //FIXME: investigate the right exception - throw Py.TypeError("Can't convert " + o.getClass().getName() + " to cmpop node"); + //throw Py.TypeError("Can't convert " + o.getClass().getName() + " to cmpop node"); } - public Object adaptIter(Object iter) { + public PyObject ast2py(Object o) { + return (PyObject)o; + } + + public List iter2ast(PyObject iter) { List<cmpopType> cmpops = new ArrayList<cmpopType>(); for(Object o : (Iterable)iter) { - cmpops.add((cmpopType)adapt(o)); + cmpops.add((cmpopType)py2ast((PyObject)o)); } return cmpops; } Modified: branches/astwrite/src/org/python/antlr/adapter/ComprehensionAdapter.java =================================================================== --- branches/astwrite/src/org/python/antlr/adapter/ComprehensionAdapter.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/adapter/ComprehensionAdapter.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -1,6 +1,7 @@ package org.python.antlr.adapter; import org.python.core.Py; +import org.python.core.PyObject; import org.python.core.PyJavaInstance; import org.python.antlr.ast.comprehensionType; @@ -10,13 +11,10 @@ public class ComprehensionAdapter implements AstAdapter { - public Object adapt(Object o) { + public Object py2ast(PyObject o) { if (o == null) { return o; } - if (o instanceof PyJavaInstance) { - o = ((PyJavaInstance)o).__tojava__(comprehensionType.class); - } if (o instanceof comprehensionType) { return o; } @@ -24,10 +22,14 @@ throw Py.TypeError("Can't convert " + o.getClass().getName() + " to comprehension node"); } - public Object adaptIter(Object iter) { + public PyObject ast2py(Object o) { + return (PyObject)o; + } + + public List iter2ast(PyObject iter) { List<comprehensionType> comprehensions = new ArrayList<comprehensionType>(); for(Object o : (Iterable)iter) { - comprehensions.add((comprehensionType)adapt(o)); + comprehensions.add((comprehensionType)py2ast((PyObject)o)); } return comprehensions; } Modified: branches/astwrite/src/org/python/antlr/adapter/ExcepthandlerAdapter.java =================================================================== --- branches/astwrite/src/org/python/antlr/adapter/ExcepthandlerAdapter.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/adapter/ExcepthandlerAdapter.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -1,6 +1,7 @@ package org.python.antlr.adapter; import org.python.core.Py; +import org.python.core.PyObject; import org.python.core.PyJavaInstance; import org.python.antlr.ast.ExceptHandler; @@ -11,13 +12,10 @@ public class ExcepthandlerAdapter implements AstAdapter { - public Object adapt(Object o) { + public Object py2ast(PyObject o) { if (o == null) { return o; } - if (o instanceof PyJavaInstance) { - o = ((PyJavaInstance)o).__tojava__(ExceptHandler.class); - } if (o instanceof ExceptHandler) { return o; } @@ -26,10 +24,14 @@ throw Py.TypeError("Can't convert " + o.getClass().getName() + " to excepthandler node"); } - public Object adaptIter(Object iter) { + public PyObject ast2py(Object o) { + return (PyObject)o; + } + + public List iter2ast(PyObject iter) { List<ExceptHandler> excepthandlers = new ArrayList<ExceptHandler>(); for(Object o : (Iterable)iter) { - excepthandlers.add((ExceptHandler)adapt(o)); + excepthandlers.add((ExceptHandler)py2ast((PyObject)o)); } return excepthandlers; } Modified: branches/astwrite/src/org/python/antlr/adapter/ExprAdapter.java =================================================================== --- branches/astwrite/src/org/python/antlr/adapter/ExprAdapter.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/adapter/ExprAdapter.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -1,9 +1,14 @@ package org.python.antlr.adapter; import org.python.core.Py; +import org.python.core.PyComplex; +import org.python.core.PyFloat; import org.python.core.PyInteger; +import org.python.core.PyLong; +import org.python.core.PyJavaInstance; +import org.python.core.PyObject; import org.python.core.PyString; -import org.python.core.PyJavaInstance; +import org.python.core.PyUnicode; import org.python.antlr.ast.exprType; import org.python.antlr.ast.Num; @@ -13,30 +18,31 @@ import java.util.List; public class ExprAdapter implements AstAdapter { - - public Object adapt(Object o) { + + public Object py2ast(PyObject o) { if (o == null) { return o; } - if (o instanceof PyJavaInstance) { - o = ((PyJavaInstance)o).__tojava__(exprType.class); - } if (o instanceof exprType) { return o; - } else if (o instanceof Integer) { - return new Num(new PyInteger((Integer)o)); - } else if (o instanceof String) { - return new Str(new PyString((String)o)); + } else if (o instanceof PyInteger || o instanceof PyLong || o instanceof PyFloat || o instanceof PyComplex) { + return new Num(o); + } else if (o instanceof PyString || o instanceof PyUnicode) { + return new Str(o); } //FIXME: investigate the right exception throw Py.TypeError("Can't convert " + o.getClass().getName() + " to expr node"); } - public Object adaptIter(Object iter) { + public PyObject ast2py(Object o) { + return (PyObject)o; + } + + public List iter2ast(PyObject iter) { List<exprType> exprs = new ArrayList<exprType>(); for(Object o : (Iterable)iter) { - exprs.add((exprType)adapt(o)); + exprs.add((exprType)py2ast((PyObject)o)); } return exprs; } Modified: branches/astwrite/src/org/python/antlr/adapter/IdentifierAdapter.java =================================================================== --- branches/astwrite/src/org/python/antlr/adapter/IdentifierAdapter.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/adapter/IdentifierAdapter.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -2,6 +2,7 @@ import org.python.core.Py; import org.python.core.PyJavaInstance; +import org.python.core.PyObject; import org.python.antlr.ast.Num; @@ -10,25 +11,18 @@ public class IdentifierAdapter implements AstAdapter { - public Object adapt(Object o) { - if (o == null) { - return o; - } - if (o instanceof PyJavaInstance) { - o = ((PyJavaInstance)o).__tojava__(String.class); - } - if (o instanceof String) { - return o; - } + public Object py2ast(PyObject o) { + return o.toString(); + } - //FIXME: investigate the right exception - throw Py.TypeError("Can't convert " + o.getClass().getName() + " to identifier node"); + public PyObject ast2py(Object o) { + return (PyObject)o; } - public Object adaptIter(Object iter) { + public List iter2ast(PyObject iter) { List<String> identifiers = new ArrayList<String>(); for(Object o : (Iterable)iter) { - identifiers.add((String)adapt(o)); + identifiers.add((String)py2ast((PyObject)o)); } return identifiers; } Modified: branches/astwrite/src/org/python/antlr/adapter/KeywordAdapter.java =================================================================== --- branches/astwrite/src/org/python/antlr/adapter/KeywordAdapter.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/adapter/KeywordAdapter.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -2,6 +2,7 @@ import org.python.core.Py; import org.python.core.PyJavaInstance; +import org.python.core.PyObject; import org.python.antlr.ast.keywordType; @@ -10,13 +11,10 @@ public class KeywordAdapter implements AstAdapter { - public Object adapt(Object o) { + public Object py2ast(PyObject o) { if (o == null) { return o; } - if (o instanceof PyJavaInstance) { - o = ((PyJavaInstance)o).__tojava__(keywordType.class); - } if (o instanceof keywordType) { return o; } @@ -25,10 +23,14 @@ throw Py.TypeError("Can't convert " + o.getClass().getName() + " to keyword node"); } - public Object adaptIter(Object iter) { + public PyObject ast2py(Object o) { + return (PyObject)o; + } + + public List iter2ast(PyObject iter) { List<keywordType> keywords = new ArrayList<keywordType>(); for(Object o : (Iterable)iter) { - keywords.add((keywordType)adapt(o)); + keywords.add((keywordType)py2ast((PyObject)o)); } return keywords; } Deleted: branches/astwrite/src/org/python/antlr/adapter/ListWrapper.java =================================================================== --- branches/astwrite/src/org/python/antlr/adapter/ListWrapper.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/adapter/ListWrapper.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -1,226 +0,0 @@ -package org.python.antlr.adapter; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.python.core.Py; -import org.python.core.PyObject; -import org.python.core.PySequence; - -public class ListWrapper implements List { - - private List list; - private AstAdapter adapter; - - public ListWrapper(List list) { - this(list, null); - } - - public ListWrapper(List list, AstAdapter adapter) { - if (list == null) { - throw Py.TypeError("AST list can't be None"); - } - this.list = list; - this.adapter = adapter; - } - - public boolean containsAll(Collection c) { - return containsAll(c); - } - - public boolean removeAll(Collection c) { - return list.removeAll(c); - } - - public boolean retainAll(Collection c) { - return list.retainAll(c); - } - - public boolean add(Object e) { - return list.add(e); - } - - public void add(int index, Object e) { - list.add(index, e); - } - - public boolean addAll(Collection c) { - return list.addAll(c); - } - - public boolean addAll(int index, Collection c) { - return list.addAll(index, c); - } - - public void clear() { - list.clear(); - } - - public boolean contains(Object elem) { - return list.contains(elem); - } - - public Object get(int index) { - return list.get(index); - } - - public int indexOf(Object elem) { - return list.indexOf(elem); - } - - public boolean isEmpty() { - return list.isEmpty(); - } - - public int lastIndexOf(Object elem) { - return list.lastIndexOf(elem); - } - - public Object remove(int index) { - return list.remove(index); - } - - public boolean remove(Object o) { - return list.remove(o); - } - - public Object set(int index, Object element) { - return list.set(index, element); - } - - public int size() { - return list.size(); - } - - public Object[] toArray() { - return list.toArray(); - } - - public Object[] toArray(Object[] a) { - return list.toArray(a); - } - - public Iterator iterator() { - return list.iterator(); - } - - public ListIterator listIterator() { - return list.listIterator(); - } - - public ListIterator listIterator(int index) { - return list.listIterator(index); - } - - public List subList(int fromIndex, int toIndex) { - return list.subList(fromIndex, toIndex); - } - - /* - public ListWrapper __add__(Object o) { - List newList = new ArrayList(); - newList.addAll(list); - newList.add(o); - return new ListWrapper(newList); - } - - public int __len__() { - return list.size(); - } - - public boolean __contains__(Object o) { - return list.contains(o); - } - - public PyObject __imul__(PyObject o) { - throw new UnsupportedOperationException("1 Not supported yet."); - } - - public PyObject __iter__() { - throw new UnsupportedOperationException("2 Not supported yet."); - } - - public PyObject __mul__(PyObject o) { - throw new UnsupportedOperationException("3 Not supported yet."); - } - - public PyObject __radd__(PyObject o) { - throw new UnsupportedOperationException("4 Not supported yet."); - } - - public PyObject __rmul__(PyObject o) { - throw new UnsupportedOperationException("5 Not supported yet."); - } - */ - - public void append(PyObject o) { - list.add(adapter.adapt(o)); - } - - public int count(PyObject o) { - throw new UnsupportedOperationException("6 Not supported yet."); - } - - protected void del(int i) { - throw new UnsupportedOperationException("7 Not supported yet."); - } - - protected void delRange(int start, int stop, int step) { - throw new UnsupportedOperationException("8 Not supported yet."); - } - - public void extend(PyObject o) { - throw new UnsupportedOperationException("9 Not supported yet."); - } - - public int index(PyObject o) { - throw new UnsupportedOperationException("10 Not supported yet."); - } - - public int index(PyObject o, int start) { - throw new UnsupportedOperationException("11 Not supported yet."); - } - - public int index(PyObject o, int start, int stop) { - throw new UnsupportedOperationException("12 Not supported yet."); - } - - public void insert(int index, PyObject o) { - throw new UnsupportedOperationException("13 Not supported yet."); - } - - public PyObject pop() { - throw new UnsupportedOperationException("14 Not supported yet."); - } - - public PyObject pop(int n) { - throw new UnsupportedOperationException("15 Not supported yet."); - } - - public void remove(PyObject o) { - throw new UnsupportedOperationException("16 Not supported yet."); - } - - public void reverse() { - throw new UnsupportedOperationException("17 Not supported yet."); - } - - public void sort(PyObject compare) { - throw new UnsupportedOperationException("18 Not supported yet."); - } - - public void sort() { - throw new UnsupportedOperationException("19 Not supported yet."); - } - - public void sort(PyObject cmp, PyObject key, PyObject reverse) { - throw new UnsupportedOperationException("20 Not supported yet."); - } - - public String toString() { - return list.toString(); - } -} Modified: branches/astwrite/src/org/python/antlr/adapter/SliceAdapter.java =================================================================== --- branches/astwrite/src/org/python/antlr/adapter/SliceAdapter.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/adapter/SliceAdapter.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -2,6 +2,7 @@ import org.python.core.Py; import org.python.core.PyJavaInstance; +import org.python.core.PyObject; import org.python.antlr.ast.sliceType; import org.python.antlr.ast.Num; @@ -11,13 +12,10 @@ public class SliceAdapter implements AstAdapter { - public Object adapt(Object o) { + public Object py2ast(PyObject o) { if (o == null) { return o; } - if (o instanceof PyJavaInstance) { - o = ((PyJavaInstance)o).__tojava__(sliceType.class); - } if (o instanceof sliceType) { return o; } @@ -26,10 +24,14 @@ throw Py.TypeError("Can't convert " + o.getClass().getName() + " to slice node"); } - public Object adaptIter(Object iter) { + public PyObject ast2py(Object o) { + return (PyObject)o; + } + + public List iter2ast(PyObject iter) { List<sliceType> slices = new ArrayList<sliceType>(); for(Object o : (Iterable)iter) { - slices.add((sliceType)adapt(o)); + slices.add((sliceType)py2ast((PyObject)o)); } return slices; } Modified: branches/astwrite/src/org/python/antlr/adapter/StmtAdapter.java =================================================================== --- branches/astwrite/src/org/python/antlr/adapter/StmtAdapter.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/adapter/StmtAdapter.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -2,6 +2,7 @@ import org.python.core.Py; import org.python.core.PyJavaInstance; +import org.python.core.PyObject; import org.python.antlr.ast.stmtType; @@ -10,13 +11,10 @@ public class StmtAdapter implements AstAdapter { - public Object adapt(Object o) { + public Object py2ast(PyObject o) { if (o == null) { return o; } - if (o instanceof PyJavaInstance) { - o = ((PyJavaInstance)o).__tojava__(stmtType.class); - } if (o instanceof stmtType) { return o; } @@ -24,10 +22,14 @@ throw Py.TypeError("Can't convert " + o.getClass().getName() + " to stmt node"); } - public Object adaptIter(Object iter) { + public PyObject ast2py(Object o) { + return (PyObject)o; + } + + public List iter2ast(PyObject iter) { List<stmtType> stmts = new ArrayList<stmtType>(); for(Object o : (Iterable)iter) { - stmts.add((stmtType)adapt(o)); + stmts.add((stmtType)py2ast((PyObject)o)); } return stmts; } Modified: branches/astwrite/src/org/python/antlr/ast/Assert.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Assert.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/ast/Assert.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -1,12 +1,13 @@ // Autogenerated AST node package org.python.antlr.ast; +import org.antlr.runtime.CommonToken; +import org.antlr.runtime.Token; import org.python.antlr.PythonTree; import org.python.antlr.adapter.AstAdapters; -import org.python.antlr.adapter.ListWrapper; -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.Token; +import org.python.core.AstList; import org.python.core.Py; import org.python.core.PyObject; +import org.python.core.PyString; import org.python.core.PyType; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; @@ -26,10 +27,10 @@ } @ExposedGet(name = "test") public PyObject getTest() { - return Py.None; + return test; } @ExposedSet(name = "test") - public void setTest(Object test) { + public void setTest(PyObject test) { this.test = AstAdapters.to_expr(test); } @@ -39,10 +40,10 @@ } @ExposedGet(name = "msg") public PyObject getMsg() { - return Py.None; + return msg; } @ExposedSet(name = "msg") - public void setMsg(Object msg) { + public void setMsg(PyObject msg) { this.msg = AstAdapters.to_expr(msg); } @@ -59,7 +60,7 @@ @ExposedNew @ExposedMethod public void Module___init__(PyObject[] args, String[] keywords) {} - public Assert(Object test, Object msg) { + public Assert(PyObject test, PyObject msg) { setTest(test); setMsg(msg); } Modified: branches/astwrite/src/org/python/antlr/ast/Assign.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Assign.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/ast/Assign.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -1,12 +1,13 @@ // Autogenerated AST node package org.python.antlr.ast; +import org.antlr.runtime.CommonToken; +import org.antlr.runtime.Token; import org.python.antlr.PythonTree; import org.python.antlr.adapter.AstAdapters; -import org.python.antlr.adapter.ListWrapper; -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.Token; +import org.python.core.AstList; import org.python.core.Py; import org.python.core.PyObject; +import org.python.core.PyString; import org.python.core.PyType; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; @@ -26,10 +27,10 @@ } @ExposedGet(name = "targets") public PyObject getTargets() { - return Py.None; + return new AstList(targets, AstAdapters.exprAdapter); } @ExposedSet(name = "targets") - public void setTargets(Object targets) { + public void setTargets(PyObject targets) { //FJW this.targets = AstAdapters.to_exprList(targets); } @@ -39,10 +40,10 @@ } @ExposedGet(name = "value") public PyObject getValue() { - return Py.None; + return value; } @ExposedSet(name = "value") - public void setValue(Object value) { + public void setValue(PyObject value) { this.value = AstAdapters.to_expr(value); } @@ -59,7 +60,7 @@ @ExposedNew @ExposedMethod public void Module___init__(PyObject[] args, String[] keywords) {} - public Assign(Object targets, Object value) { + public Assign(PyObject targets, PyObject value) { setTargets(targets); setValue(value); } Modified: branches/astwrite/src/org/python/antlr/ast/AstModule.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/AstModule.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/ast/AstModule.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -3,7 +3,10 @@ import org.python.core.ClassDictInit; import org.python.core.imp; import org.python.core.Py; +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.antlr.AST; @@ -14,6 +17,11 @@ private AstModule() {} public static void classDictInit(PyObject dict) { + dict.__setitem__("__doc__", Py.None); + dict.__setitem__("__name__", new PyString("_ast")); + dict.__setitem__("__version__", new PyString("62047")); + dict.__setitem__("PyCF_ONLY_AST", new PyInteger(PyTableCode.PyCF_ONLY_AST)); + dict.__setitem__("AST", AST.TYPE); dict.__setitem__("Module", Module.TYPE); dict.__setitem__("Assert", Assert.TYPE); @@ -80,7 +88,51 @@ dict.__setitem__("mod", modType.TYPE); dict.__setitem__("slice", sliceType.TYPE); dict.__setitem__("stmt", stmtType.TYPE); + dict.__setitem__("operator", imp.importName("org.python.antlr.ast.operatorType", false)); dict.__setitem__("Add", imp.importName("org.python.antlr.ast.operatorType.Add", false)); + dict.__setitem__("Sub", imp.importName("org.python.antlr.ast.operatorType.Sub", false)); + dict.__setitem__("Mult", imp.importName("org.python.antlr.ast.operatorType.Mult", false)); + dict.__setitem__("Div", imp.importName("org.python.antlr.ast.operatorType.Div", false)); + dict.__setitem__("FloorDiv", imp.importName("org.python.antlr.ast.operatorType.FloorDiv", false)); + dict.__setitem__("Mod", imp.importName("org.python.antlr.ast.operatorType.Mod", false)); + dict.__setitem__("LShift", imp.importName("org.python.antlr.ast.operatorType.LShift", false)); + dict.__setitem__("RShift", imp.importName("org.python.antlr.ast.operatorType.RShift", false)); + dict.__setitem__("BitOr", imp.importName("org.python.antlr.ast.operatorType.BitOr", false)); + dict.__setitem__("BitAnd", imp.importName("org.python.antlr.ast.operatorType.BitAnd", false)); + dict.__setitem__("BitXor", imp.importName("org.python.antlr.ast.operatorType.BitXor", false)); + dict.__setitem__("Pow", imp.importName("org.python.antlr.ast.operatorType.Pow", false)); + + dict.__setitem__("boolop", imp.importName("org.python.antlr.ast.boolopType", false)); + dict.__setitem__("And", imp.importName("org.python.antlr.ast.boolopType.And", false)); + dict.__setitem__("Or", imp.importName("org.python.antlr.ast.boolopType.Or", false)); + + dict.__setitem__("cmpop", imp.importName("org.python.antlr.ast.cmpopType", false)); + dict.__setitem__("Eq", imp.importName("org.python.antlr.ast.cmpopType.Eq", false)); + dict.__setitem__("Gt", imp.importName("org.python.antlr.ast.cmpopType.Gt", false)); + dict.__setitem__("GtE", imp.importName("org.python.antlr.ast.cmpopType.GtE", false)); + dict.__setitem__("In", imp.importName("org.python.antlr.ast.cmpopType.In", false)); + dict.__setitem__("Is", imp.importName("org.python.antlr.ast.cmpopType.Is", false)); + dict.__setitem__("IsNot", imp.importName("org.python.antlr.ast.cmpopType.IsNot", false)); + dict.__setitem__("Lt", imp.importName("org.python.antlr.ast.cmpopType.Lt", false)); + dict.__setitem__("LtE", imp.importName("org.python.antlr.ast.cmpopType.LtE", false)); + dict.__setitem__("NotEq", imp.importName("org.python.antlr.ast.cmpopType.NotEq", false)); + dict.__setitem__("NotIn", imp.importName("org.python.antlr.ast.cmpopType.NotIn", false)); + + dict.__setitem__("expr_context", imp.importName("org.python.antlr.ast.expr_contextType", false)); + dict.__setitem__("Load", imp.importName("org.python.antlr.ast.expr_contextType.Load", false)); + dict.__setitem__("Store", imp.importName("org.python.antlr.ast.expr_contextType.Store", false)); + dict.__setitem__("Del", imp.importName("org.python.antlr.ast.expr_contextType.Del", false)); + dict.__setitem__("AugLoad", imp.importName("org.python.antlr.ast.expr_contextType.AugLoad", false)); + dict.__setitem__("AugStore", imp.importName("org.python.antlr.ast.expr_contextType.AugStore", false)); + dict.__setitem__("Param", imp.importName("org.python.antlr.ast.expr_contextType.Param", false)); + + dict.__setitem__("unaryop", imp.importName("org.python.antlr.ast.unaryopType", false)); + dict.__setitem__("Invert", imp.importName("org.python.antlr.ast.unaryopType.Invert", false)); + dict.__setitem__("Not", imp.importName("org.python.antlr.ast.unaryopType.Not", false)); + dict.__setitem__("UAdd", imp.importName("org.python.antlr.ast.unaryopType.UAdd", false)); + dict.__setitem__("USub", imp.importName("org.python.antlr.ast.unaryopType.USub", false)); + + dict.__setitem__("classDictInit", null); } } Modified: branches/astwrite/src/org/python/antlr/ast/Attribute.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Attribute.java 2008-12-01 23:33:55 UTC (rev 5671) +++ branches/astwrite/src/org/python/antlr/ast/Attribute.java 2008-12-02 03:31:45 UTC (rev 5672) @@ -1,12 +1,13 @@ // Autogenerated AST node package org.python.antlr.ast; +import org.antlr.runtime.CommonToken; +import org.antlr.runtime.Token; import org.python.antlr.PythonTree; import org.python.antlr.adapter.AstAdapters; -import org.python.antlr.adapter.ListWrapper; -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.Token; +import org.python.core.AstList; import org.python.core.Py; import org.python.core.PyObject; +import org.python.core.PyString; import org.python.core.PyType; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; @@ -26,10 +27,10 @@ } @ExposedGet(name = "value") public PyObject getValue() { - return Py.None; + return value; } @ExposedSet(name = ... [truncated message content] |
From: <otm...@us...> - 2008-12-01 23:33:57
|
Revision: 5671 http://jython.svn.sourceforge.net/jython/?rev=5671&view=rev Author: otmarhumbel Date: 2008-12-01 23:33:55 +0000 (Mon, 01 Dec 2008) Log Message: ----------- dump system properties to a file (in verbose mode) Modified Paths: -------------- trunk/installer/src/java/org/python/util/install/Installation.java Modified: trunk/installer/src/java/org/python/util/install/Installation.java =================================================================== --- trunk/installer/src/java/org/python/util/install/Installation.java 2008-12-01 18:33:00 UTC (rev 5670) +++ trunk/installer/src/java/org/python/util/install/Installation.java 2008-12-01 23:33:55 UTC (rev 5671) @@ -6,6 +6,7 @@ import java.io.FilenameFilter; import java.io.IOException; import java.text.MessageFormat; +import java.util.Enumeration; import java.util.Locale; import java.util.Properties; import java.util.ResourceBundle; @@ -326,6 +327,7 @@ try { boolean earlyVerbose = InstallerCommandLine.hasVerboseOptionInArgs(args); if (earlyVerbose) { + dumpSystemProperties(); ConsoleInstaller.message("reading jar info"); } JarInfo jarInfo = new JarInfo(); @@ -371,5 +373,23 @@ System.exit(1); } } + + private static void dumpSystemProperties() throws IOException { + @SuppressWarnings("unchecked") + Enumeration<String> names = (Enumeration<String>)System.getProperties().propertyNames(); + StringBuilder contents = new StringBuilder(400); + contents.append("Properties at the beginning of the Jython installation:\n\n"); + while (names.hasMoreElements()) { + String name = names.nextElement(); + String value = System.getProperty(name, ""); + contents.append(name); + contents.append('='); + contents.append(value); + contents.append("\n"); + } + File output = File.createTempFile("System", ".properties"); + FileHelper.write(output, contents.toString()); + ConsoleInstaller.message("system properties dumped to " + output.getAbsolutePath()); + } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <nr...@us...> - 2008-12-01 18:33:05
|
Revision: 5670 http://jython.svn.sourceforge.net/jython/?rev=5670&view=rev Author: nriley Date: 2008-12-01 18:33:00 +0000 (Mon, 01 Dec 2008) Log Message: ----------- PyStringMap should not be hashable, just as PyDictionary isn't. Modified Paths: -------------- trunk/jython/Lib/test/test_stringmap.py trunk/jython/src/org/python/core/PyStringMap.java Modified: trunk/jython/Lib/test/test_stringmap.py =================================================================== --- trunk/jython/Lib/test/test_stringmap.py 2008-12-01 01:14:21 UTC (rev 5669) +++ trunk/jython/Lib/test/test_stringmap.py 2008-12-01 18:33:00 UTC (rev 5670) @@ -62,7 +62,10 @@ for i in r.keys(): self.assert_(d.has_key(i)) self.assert_(i in d) - + + # Test unhashability + self.assertRaises(TypeError, hash, d) + def test_stringmap_in_mapping(self): class A: def __init__(self): Modified: trunk/jython/src/org/python/core/PyStringMap.java =================================================================== --- trunk/jython/src/org/python/core/PyStringMap.java 2008-12-01 01:14:21 UTC (rev 5669) +++ trunk/jython/src/org/python/core/PyStringMap.java 2008-12-01 18:33:00 UTC (rev 5670) @@ -500,4 +500,8 @@ return pyKey; } } + + public int hashCode() { + throw Py.TypeError(String.format("unhashable type: '%.200s'", getType().fastGetName())); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-01 01:14:25
|
Revision: 5669 http://jython.svn.sourceforge.net/jython/?rev=5669&view=rev Author: cgroves Date: 2008-12-01 01:14:21 +0000 (Mon, 01 Dec 2008) Log Message: ----------- Reset a PyJavaType's state when reload is called on it. This was just ignored on PyJavaClasses, so this is a little step up Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/PyObject.java branches/newstyle-java-types/src/org/python/core/__builtin__.java Modified: branches/newstyle-java-types/src/org/python/core/PyObject.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-12-01 01:08:51 UTC (rev 5668) +++ branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-12-01 01:14:21 UTC (rev 5669) @@ -618,7 +618,6 @@ * @param value the value to set this key to **/ public void __setitem__(PyObject key, PyObject value) { - Thread.dumpStack(); throw Py.TypeError(String.format("'%.200s' object does not support item assignment", getType().fastGetName())); } Modified: branches/newstyle-java-types/src/org/python/core/__builtin__.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/__builtin__.java 2008-12-01 01:08:51 UTC (rev 5668) +++ branches/newstyle-java-types/src/org/python/core/__builtin__.java 2008-12-01 01:14:21 UTC (rev 5669) @@ -97,6 +97,8 @@ if (o == Py.NoConversion) { if (arg1 instanceof PySystemState) { return __builtin__.reload((PySystemState)arg1); + } else if(arg1 instanceof PyJavaType) { + return __builtin__.reload((PyJavaType)arg1); } throw Py.TypeError("reload() argument must be a module"); } @@ -1105,6 +1107,12 @@ return o; } + public static PyObject reload(PyJavaType o) { + // Reset the contents of our dict to the state from our class + o.init(); + return o; + } + public static PyString repr(PyObject o) { return o.__repr__(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-01 01:09:00
|
Revision: 5668 http://jython.svn.sourceforge.net/jython/?rev=5668&view=rev Author: cgroves Date: 2008-12-01 01:08:51 +0000 (Mon, 01 Dec 2008) Log Message: ----------- Go ahead and take multiple methods in PyReflectedFunction's constructor Modified Paths: -------------- branches/newstyle-java-types/Lib/test/test_joverload.py branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java Modified: branches/newstyle-java-types/Lib/test/test_joverload.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_joverload.py 2008-12-01 01:06:33 UTC (rev 5667) +++ branches/newstyle-java-types/Lib/test/test_joverload.py 2008-12-01 01:08:51 UTC (rev 5668) @@ -11,9 +11,7 @@ class PyReflFuncEnvl: def __init__(self,name,meths): - self.reflfunc = PyReflectedFunction(meths[0]) - for meth in meths[1:]: - self.reflfunc.addMethod(meth) + self.reflfunc = PyReflectedFunction(meths) def __call__(self,inst,args): return self.reflfunc(inst,*args) Modified: branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java 2008-12-01 01:06:33 UTC (rev 5667) +++ branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java 2008-12-01 01:08:51 UTC (rev 5668) @@ -21,12 +21,16 @@ __name__ = name; } - public PyReflectedFunction(Method method) { - this(method.getName()); - addMethod(method); + public PyReflectedFunction(Method... methods) { + this(methods[0].getName()); + for (Method meth : methods) { + addMethod(meth); + } if (nargs == 0) { String msg = String.format("Attempted to make Java method visible, but it isn't " - + "callable[method=%s, class=%s]", method.getName(), method.getDeclaringClass()); + + "callable[method=%s, class=%s]", + methods[0].getName(), + methods[0].getDeclaringClass()); throw Py.SystemError(msg); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-01 01:06:36
|
Revision: 5667 http://jython.svn.sourceforge.net/jython/?rev=5667&view=rev Author: cgroves Date: 2008-12-01 01:06:33 +0000 (Mon, 01 Dec 2008) Log Message: ----------- PyReflectedFunction no longer exposes a String constructor Modified Paths: -------------- branches/newstyle-java-types/Lib/test/test_joverload.py Modified: branches/newstyle-java-types/Lib/test/test_joverload.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_joverload.py 2008-12-01 01:00:37 UTC (rev 5666) +++ branches/newstyle-java-types/Lib/test/test_joverload.py 2008-12-01 01:06:33 UTC (rev 5667) @@ -6,13 +6,13 @@ import unittest import java -import org.python.core +from org.python.core import PyReflectedFunction class PyReflFuncEnvl: def __init__(self,name,meths): - self.reflfunc = org.python.core.PyReflectedFunction(name) - for meth in meths: + self.reflfunc = PyReflectedFunction(meths[0]) + for meth in meths[1:]: self.reflfunc.addMethod(meth) def __call__(self,inst,args): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-01 01:00:40
|
Revision: 5666 http://jython.svn.sourceforge.net/jython/?rev=5666&view=rev Author: cgroves Date: 2008-12-01 01:00:37 +0000 (Mon, 01 Dec 2008) Log Message: ----------- Replace fillDict with init which encapsulates all the differences between PyType and PyJavaType initialization. Have bootstrap types use init as well to remove the duplication of type builder initialization. Include interfaces and superclasses in the mro of wrapped Java types. Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/PyJavaType.java branches/newstyle-java-types/src/org/python/core/PyType.java Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-12-01 00:38:14 UTC (rev 5665) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-12-01 01:00:37 UTC (rev 5666) @@ -11,6 +11,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; + import org.python.core.util.StringUtil; import org.python.expose.ExposeAsSuperclass; import org.python.util.Generic; @@ -37,15 +39,56 @@ } @Override - protected void fillDict() { + protected void init() { + name = underlying_class.getName(); + // Strip the java fully qualified class name from Py classes in core + if (name.startsWith("org.python.core.Py")) { + name = name.substring("org.python.core.Py".length()).toLowerCase(); + } dict = new PyStringMap(); - Class<?> base = underlying_class.getSuperclass(); + Class<?> baseClass = underlying_class.getSuperclass(); + if (PyObject.class.isAssignableFrom(underlying_class)) { + // Non-exposed subclasses of PyObject use a simple linear mro to PyObject that ignores + // their interfaces + computeLinearMro(baseClass); + } else { + // Wrapped Java types fill in their mro first using their base class and then all of + // their interfaces. + if (baseClass == null) { + base = PyType.fromClass(PyObject.class); + } else { + base = PyType.fromClass(baseClass); + } + bases = new PyObject[1 + underlying_class.getInterfaces().length]; + bases[0] = base; + for (int i = 1; i < bases.length; i++) { + bases[i] = PyType.fromClass(underlying_class.getInterfaces()[i - 1]); + } + Set<PyObject> seen = Generic.set(); + List<PyObject> mros = Generic.list(); + mros.add(this); + for (PyObject obj : bases) { + for (PyObject mroObj : ((PyType)obj).mro) { + if (seen.add(mroObj)) { + mros.add(mroObj); + } + } + } + mro = mros.toArray(new PyObject[mros.size()]); + } + // PyReflected* can't call or access anything from non-public classes that aren't in + // org.python.core + if (!Modifier.isPublic(underlying_class.getModifiers()) && + !name.startsWith("org.python.core")) { + return; + } + // Add methods and determine bean properties declared on this class Map<String, PyBeanProperty> props = Generic.map(); Map<String, PyBeanEvent> events = Generic.map(); for (Method meth : underlying_class.getMethods()) { - if (!declaredOnMember(base, meth) || ignore(meth)) { + if (!declaredOnMember(baseClass, meth) || ignore(meth)) { continue; } String methname = meth.getName(); @@ -75,7 +118,7 @@ ename = ename.substring(idot + 1); } ename = normalize(StringUtil.decapitalize(ename)); - events.put(ename, new PyBeanEvent(name, eventClass, meth)); + events.put(ename, new PyBeanEvent(ename, eventClass, meth)); continue; } @@ -118,7 +161,7 @@ // Add fields declared on this type for (Field field : underlying_class.getFields()) { - if (!declaredOnMember(base, field)) { + if (!declaredOnMember(baseClass, field)) { continue; } String fldname = field.getName(); @@ -219,7 +262,7 @@ throw Py.JavaError(exc); } } - if (base != Object.class) { + if (baseClass != Object.class) { has_set = getDescrMethod(underlying_class, "__set__", OO) != null || getDescrMethod(underlying_class, "_doset", OO) != null; has_delete = getDescrMethod(underlying_class, "__delete__", PyObject.class) != null Modified: branches/newstyle-java-types/src/org/python/core/PyType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyType.java 2008-12-01 00:38:14 UTC (rev 5665) +++ branches/newstyle-java-types/src/org/python/core/PyType.java 2008-12-01 01:00:37 UTC (rev 5666) @@ -333,36 +333,55 @@ return newobj; } - protected void fillDict() { + /** + * Called on builtin types after underlying_class has been set on them. Should fill in dict, + * name, mro, base and bases from the class. + */ + protected void init() { + if (underlying_class == PyObject.class) { + mro = new PyType[] {this}; + } else { + Class<?> baseClass; + if (!Py.BOOTSTRAP_TYPES.contains(underlying_class)) { + baseClass = classToBuilder.get(underlying_class).getBase(); + } else { + baseClass = PyObject.class; + } + if (baseClass == Object.class) { + baseClass = underlying_class.getSuperclass(); + } + computeLinearMro(baseClass); + } if (Py.BOOTSTRAP_TYPES.contains(underlying_class)) { + // init will be called again from addBuilder which also removes underlying_class from + // BOOTSTRAP_TYPES return; } - dict = classToBuilder.get(underlying_class).getDict(this); + TypeBuilder builder = classToBuilder.get(underlying_class); + name = builder.getName(); + dict = builder.getDict(this); + setIsBaseType(builder.getIsBaseType()); instantiable = dict.__finditem__("__new__") != null; fillHasSetAndDelete(); } + /** + * Fills the base and bases of this type with the type of baseClass as sets its mro to this type + * followed by the mro of baseClass. + */ + protected void computeLinearMro(Class<?> baseClass) { + base = PyType.fromClass(baseClass); + mro = new PyType[base.mro.length + 1]; + System.arraycopy(base.mro, 0, mro, 1, base.mro.length); + mro[0] = this; + bases = new PyObject[] {base}; + } + private void fillHasSetAndDelete() { has_set = lookup("__set__") != null; has_delete = lookup("__delete__") != null; } - private static void fillInMRO(PyType type, Class<?> base) { - if (type.underlying_class == PyObject.class) { - type.mro = new PyType[] {type}; - return; - } - if (base == null) { - base = PyObject.class; - } - PyType baseType = fromClass(base); - type.mro = new PyType[baseType.mro.length + 1]; - System.arraycopy(baseType.mro, 0, type.mro, 1, baseType.mro.length); - type.mro[0] = type; - type.base = baseType; - type.bases = new PyObject[] {baseType}; - } - public PyObject getStatic() { PyType cur = this; while (cur.underlying_class == null) { @@ -951,16 +970,7 @@ } // The types in Py.BOOTSTRAP_TYPES are initialized before their builders are assigned, // so do the work of addFromClass & fillFromClass after the fact - PyType objType = fromClass(builder.getTypeClass()); - objType.name = builder.getName(); - objType.dict = builder.getDict(objType); - objType.setIsBaseType(builder.getIsBaseType()); - Class<?> base = builder.getBase(); - if (base == Object.class) { - base = forClass.getSuperclass(); - } - fillInMRO(objType, base); - objType.instantiable = objType.dict.__finditem__("__new__") != null; + fromClass(builder.getTypeClass()).init(); } } @@ -970,29 +980,14 @@ class_to_type.put(c, exposedAs); return exposedAs; } - Class<?> base = null; - boolean isBaseType = true; - String name = null; - TypeBuilder tb = getBuilder(c); - if (tb != null) { - name = tb.getName(); - isBaseType = tb.getIsBaseType(); - if (!tb.getBase().equals(Object.class)) { - base = tb.getBase(); - } - } - PyType type = class_to_type.get(c); - if (type == null) { - type = createType(c, base, name, isBaseType); - } - return type; + return createType(c); } private static TypeBuilder getBuilder(Class<?> c) { return classToBuilder == null ? null : classToBuilder.get(c); } - private static PyType createType(Class<?> c, Class<?> base, String name, boolean isBaseType) { + private static PyType createType(Class<?> c) { PyType newtype; if (c == PyType.class) { newtype = new PyType(false); @@ -1009,28 +1004,9 @@ } class_to_type.put(c, newtype); - if (base == null) { - base = c.getSuperclass(); - } newtype.underlying_class = c; - if (name == null) { - name = c.getName(); - // Strip the java fully qualified class name (specifically remove org.python.core.Py or - // fallback to stripping to the last dot) - if (name.startsWith("org.python.core.Py")) { - name = name.substring("org.python.core.Py".length()).toLowerCase(); - } else if(newtype.getProxyType() == null) { - int lastDot = name.lastIndexOf('.'); - if (lastDot != -1) { - name = name.substring(lastDot + 1); - } - } - } - newtype.name = name; newtype.builtin = true; - newtype.setIsBaseType(isBaseType); - fillInMRO(newtype, base); // basic mro, base, bases - newtype.fillDict(); + newtype.init(); return newtype; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-01 00:38:20
|
Revision: 5665 http://jython.svn.sourceforge.net/jython/?rev=5665&view=rev Author: cgroves Date: 2008-12-01 00:38:14 +0000 (Mon, 01 Dec 2008) Log Message: ----------- Merged revisions 5565,5568-5584,5593,5596,5598-5604,5606,5608-5611,5616,5618-5621,5624,5626-5627,5629-5630,5639-5640,5644-5648,5655,5661 via svnmerge from https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython ........ r5565 | fwierzbicki | 2008-11-09 19:36:31 -0800 (Sun, 09 Nov 2008) | 4 lines Just enough AST tweaking to get some of sympy working for Ondrej. On my todo list is to look at Python 2.6's ast testing and see if I can port that over to Jython. ........ r5568 | fwierzbicki | 2008-11-10 07:33:23 -0800 (Mon, 10 Nov 2008) | 2 lines remove dead code. ........ r5569 | fwierzbicki | 2008-11-10 13:12:29 -0800 (Mon, 10 Nov 2008) | 2 lines Make lineno and col_offset writable. ........ r5570 | fwierzbicki | 2008-11-11 09:48:27 -0800 (Tue, 11 Nov 2008) | 4 lines Tor Norbye found this ancient typo just by pointing NetBeans and the latest nbpython at datetime.py. Maybe there is something to be said for these "IDE"s that I keep hearing about :). ........ r5571 | otmarhumbel | 2008-11-11 15:25:25 -0800 (Tue, 11 Nov 2008) | 1 line detect JYTHON_HOME if called from the /bin directory ........ r5572 | pjenvey | 2008-11-11 17:31:02 -0800 (Tue, 11 Nov 2008) | 2 lines more java integration unicode vs str fixes ........ r5573 | fwierzbicki | 2008-11-12 11:10:54 -0800 (Wed, 12 Nov 2008) | 2 lines Upgrade to antlr-3.1.1. ........ r5574 | fwierzbicki | 2008-11-12 11:32:40 -0800 (Wed, 12 Nov 2008) | 2 lines Hopefully helping for eclipse users :). ........ r5575 | fwierzbicki | 2008-11-12 11:33:58 -0800 (Wed, 12 Nov 2008) | 3 lines Oops, try #2. That's what I get for doing this w/o having eclipse installed for verification. ........ r5576 | pjenvey | 2008-11-13 16:02:12 -0800 (Thu, 13 Nov 2008) | 2 lines fix itertools.chain stopping short with two empty iters in a row ........ r5577 | fwierzbicki | 2008-11-13 16:28:42 -0800 (Thu, 13 Nov 2008) | 2 lines Thanks to Tor Norbye for this bug fix. This was also found via NetBeans. ........ r5578 | pjenvey | 2008-11-13 23:35:53 -0800 (Thu, 13 Nov 2008) | 2 lines bring in constantine (0.3dev r80) for better errnos ........ r5579 | fwierzbicki | 2008-11-14 08:07:43 -0800 (Fri, 14 Nov 2008) | 3 lines Fix for NPE's and a weird Antlr error that can occur when Antlr is allowed to recover from parser errrors (for example, when ListErrorHandler is used). ........ r5580 | fwierzbicki | 2008-11-14 09:53:21 -0800 (Fri, 14 Nov 2008) | 2 lines Remove very old commented out code from imp.java. ........ r5581 | fwierzbicki | 2008-11-14 14:54:53 -0800 (Fri, 14 Nov 2008) | 15 lines Fix for http://bugs.jython.org/issue1141. __builtin__.__import__ had subtle differences with CPython. These differences would cause problems for those who wish to override __builtin__.__import__ statement: import hell.first_circle - CPython: ('hell.first_circle', None) - old Jython: ('hell.first_circle', ()) statement: import hell.first_circle as limbo - CPython: ('hell.first_circle', None) - old Jython: ('hell.first_circle', ('*',)) Also note that the second import statement with an "as" would return the head module instead of the tail module, the opposite of what CPython does. ........ r5582 | pjenvey | 2008-11-16 14:52:56 -0800 (Sun, 16 Nov 2008) | 3 lines fix another binop corner case -- trigger the binop 'flip' when left_type < right_type (in terms of the reversed mro) instead of left_type != right_type ........ r5583 | pjenvey | 2008-11-17 12:05:55 -0800 (Mon, 17 Nov 2008) | 4 lines o allow Socket{TCP,UDP}Test HOST/PORT to be overriden per class o use a different port than test_socket for test_select as test_socket sockopt tests don't REUSEADDR ........ r5584 | pjenvey | 2008-11-17 12:06:51 -0800 (Mon, 17 Nov 2008) | 4 lines relax the test ensuring SO_{RCV,SND}BUF matches the *exact* value we set it to after a connection was established. only for the BSDs, but we may not want to assume this anywhere ........ r5593 | pjenvey | 2008-11-20 10:52:08 -0800 (Thu, 20 Nov 2008) | 4 lines hardcode PyString encode results instead of letting java2py return unicode fixes #1177 thanks jcflack ........ r5596 | pjenvey | 2008-11-20 18:00:11 -0800 (Thu, 20 Nov 2008) | 4 lines fix handling of null prefix/exec_prefix values now that they're PyObjects fixes #1173 thanks boisgera ........ r5598 | fwierzbicki | 2008-11-22 11:18:53 -0800 (Sat, 22 Nov 2008) | 5 lines Fixes bug http://bugs.jython.org/issue1174 which reveals a corner case where CompilerFlags can come out as null. Not positive that we should be passing the "flags" value down when there is no frame, but this is probably right. Put an XXX in so it can be looked at again later. ........ r5599 | fwierzbicki | 2008-11-22 12:39:54 -0800 (Sat, 22 Nov 2008) | 3 lines Removed XXX -- looking at the code some more makes me comfortable with passing "flags" on. ........ r5600 | pjenvey | 2008-11-22 14:37:49 -0800 (Sat, 22 Nov 2008) | 3 lines from: http://svn.python.org/projects/python/branches/release25-maint/Lib/warnings.py@47273 ........ r5601 | pjenvey | 2008-11-22 15:23:48 -0800 (Sat, 22 Nov 2008) | 4 lines use the compiled filename for __file__ when appropriate. make imp responsible for setting __file__ instead of the compiler being involved fixes #1138 ........ r5602 | pjenvey | 2008-11-22 15:27:27 -0800 (Sat, 22 Nov 2008) | 3 lines from: http://svn.python.org/projects/python/branches/release25-maint/Lib/pydoc.py@54366 ........ r5603 | pjenvey | 2008-11-22 15:30:45 -0800 (Sat, 22 Nov 2008) | 3 lines o fix help -- our new isatty support confused it into using a real pager o support $py.class in ispackage ........ r5604 | cgroves | 2008-11-22 16:18:15 -0800 (Sat, 22 Nov 2008) | 1 line Assume any instance of PySequence has an accurate __len__. See http://www.nabble.com/PySequenceList-and-fastSequence-td14977175.html ........ r5606 | pjenvey | 2008-11-22 17:57:09 -0800 (Sat, 22 Nov 2008) | 5 lines o allow open({In,Out}putStream) but with a deprecation warning. make open a function o add optional bufsize args to FileUtil.wrap fixes #1171 ........ r5608 | pjenvey | 2008-11-22 20:15:40 -0800 (Sat, 22 Nov 2008) | 4 lines relax struct_time entry types to PyObject, CPython allows non ints here. mostly to get rid of __int__ calls w/ a PyInteger cast refs #1052 ........ r5609 | pjenvey | 2008-11-22 20:18:48 -0800 (Sat, 22 Nov 2008) | 6 lines ((PyInteger)obj.__int__()).getValue() -> obj.asInt() to avoid potential ClassCastException mayhem now that __int__ can return longs. as a side effect TypeErrors are raised on conversion failure rather than AttributeErrors (which is usually more appropriate anyway) fixes #1052 ........ r5610 | pjenvey | 2008-11-22 20:35:59 -0800 (Sat, 22 Nov 2008) | 4 lines zlib docs fixes #1798554, #1798556 thanks ukeshav ........ r5611 | pjenvey | 2008-11-22 22:28:45 -0800 (Sat, 22 Nov 2008) | 4 lines fix the Carlo Verre hack because open builtin classes are only cool in Ruby and JavaScript, or something like that fixes #1058 and test_descr.carloverre ........ r5616 | fwierzbicki | 2008-11-23 07:02:10 -0800 (Sun, 23 Nov 2008) | 3 lines Removed merge tracking for "svnmerge" for https://jython.svn.sourceforge.net/svnroot/jython/branches/nowalker ........ r5618 | pjenvey | 2008-11-23 11:35:19 -0800 (Sun, 23 Nov 2008) | 1 line exclude the antlr tests as they don't have any actual tests ........ r5619 | pjenvey | 2008-11-23 12:58:25 -0800 (Sun, 23 Nov 2008) | 4 lines fix bit rot in the Expose javatests: ensure we setType new descriptors, init sys when needed, fix null method docs (use "" instead) ........ r5620 | pjenvey | 2008-11-23 13:56:25 -0800 (Sun, 23 Nov 2008) | 2 lines turn on javatest/regrtest junit xml output by default, to dist/testreports ........ r5621 | pjenvey | 2008-11-23 14:22:05 -0800 (Sun, 23 Nov 2008) | 3 lines don't buffer the various popen2 helper streams in hopes to make test_cmd_line less flakey ........ r5624 | fwierzbicki | 2008-11-23 16:00:42 -0800 (Sun, 23 Nov 2008) | 3 lines Test for basic eval from a bare PythonInterpreter (was throwing an NPE) see http://bugs.jython.org/issue1174. ........ r5626 | pjenvey | 2008-11-23 18:02:47 -0800 (Sun, 23 Nov 2008) | 5 lines add an isBaseType flag to @ExposedType for toggling whether types are subclassable. disallow subclassing of builtin_function_or_method (fixes test_descr.errors). note that this requires an ant clean refs #1758319 ........ r5627 | pjenvey | 2008-11-23 18:48:33 -0800 (Sun, 23 Nov 2008) | 3 lines disallow sublcassing a number of types fixes #1758319 ........ r5629 | pjenvey | 2008-11-23 21:01:02 -0800 (Sun, 23 Nov 2008) | 4 lines from: http://svn.python.org/projects/python/branches/release25-maint/Lib/zipfile.py@60117 http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_zipfile.py@46982 ........ r5630 | pjenvey | 2008-11-23 21:02:01 -0800 (Sun, 23 Nov 2008) | 2 lines fix PyZipFile to compile to $py.class ........ r5639 | otmarhumbel | 2008-11-25 06:11:53 -0800 (Tue, 25 Nov 2008) | 2 lines to enable virtualenv again: do not hardcode JYTHON_HOME this fixes issue #1180 ........ r5640 | otmarhumbel | 2008-11-25 13:09:57 -0800 (Tue, 25 Nov 2008) | 1 line check for both jython-complete.jar and jython.jar in findRoot() ........ r5644 | pjenvey | 2008-11-26 19:30:23 -0800 (Wed, 26 Nov 2008) | 1 line update/clarify comment ........ r5645 | fwierzbicki | 2008-11-26 20:01:27 -0800 (Wed, 26 Nov 2008) | 5 lines Make PythonTree (and thus most of the ast nodes) extend PyObject instead of Antlr's CommonTree. This required pulling in much of the CommonTree code for now. Hopefully I can prune some of it out in time. Also PythonTreeAdaptor had to override more of CommonTreeAdaptor's methods. ........ r5646 | pjenvey | 2008-11-26 20:52:37 -0800 (Wed, 26 Nov 2008) | 6 lines temporarily store genexps in Java's frame instead of PyFrame. the latter could modify f_locals when cleaning up the temp slot, which causes an obscure bug if the genexp is iterating over that same f_locals (dict changed size during iteration). e.g., in a module's top level: __all__ = tuple(x for x in locals() if x.isupper()) ........ r5647 | pjenvey | 2008-11-27 12:56:10 -0800 (Thu, 27 Nov 2008) | 5 lines o explicitly convert Strings returned from ExposedGet to str (instead of unicode), just as ExposedMethod does. restores the behavior it had before the big Java integration String/unicode change o add a TypeError message for PyDataDescr.__set__ failed conversions ........ r5648 | pjenvey | 2008-11-27 12:56:40 -0800 (Thu, 27 Nov 2008) | 1 line small cleanup, match CPython's __repr__ ........ r5655 | pjenvey | 2008-11-28 13:10:39 -0800 (Fri, 28 Nov 2008) | 2 lines have exposed methods and fields convert null Strings results to Py.None ........ r5661 | pjenvey | 2008-11-28 23:43:57 -0800 (Fri, 28 Nov 2008) | 2 lines constantine-0.4 release ........ Modified Paths: -------------- branches/newstyle-java-types/.classpath branches/newstyle-java-types/Lib/datetime.py branches/newstyle-java-types/Lib/inspect.py branches/newstyle-java-types/Lib/ntpath.py branches/newstyle-java-types/Lib/os.py branches/newstyle-java-types/Lib/popen2.py branches/newstyle-java-types/Lib/posixpath.py branches/newstyle-java-types/Lib/subprocess.py branches/newstyle-java-types/Lib/test/test_bool.py branches/newstyle-java-types/Lib/test/test_chdir.py branches/newstyle-java-types/Lib/test/test_descr.py branches/newstyle-java-types/Lib/test/test_descr_jy.py branches/newstyle-java-types/Lib/test/test_fileno.py branches/newstyle-java-types/Lib/test/test_genexps.py branches/newstyle-java-types/Lib/test/test_import_jy.py branches/newstyle-java-types/Lib/test/test_inspect.py branches/newstyle-java-types/Lib/test/test_iter_jy.py branches/newstyle-java-types/Lib/test/test_select.py branches/newstyle-java-types/Lib/test/test_socket.py branches/newstyle-java-types/Lib/zlib.py branches/newstyle-java-types/ast/asdl_antlr.py branches/newstyle-java-types/build.xml branches/newstyle-java-types/grammar/Python.g branches/newstyle-java-types/src/com/ziclix/python/sql/Fetch.java branches/newstyle-java-types/src/com/ziclix/python/sql/Procedure.java branches/newstyle-java-types/src/com/ziclix/python/sql/PyCursor.java branches/newstyle-java-types/src/com/ziclix/python/sql/PyStatement.java branches/newstyle-java-types/src/org/python/antlr/AST.java branches/newstyle-java-types/src/org/python/antlr/GrammarActions.java branches/newstyle-java-types/src/org/python/antlr/ParseException.java branches/newstyle-java-types/src/org/python/antlr/PythonErrorNode.java branches/newstyle-java-types/src/org/python/antlr/PythonTree.java branches/newstyle-java-types/src/org/python/antlr/PythonTreeAdaptor.java branches/newstyle-java-types/src/org/python/antlr/ast/Assert.java branches/newstyle-java-types/src/org/python/antlr/ast/Assign.java branches/newstyle-java-types/src/org/python/antlr/ast/Attribute.java branches/newstyle-java-types/src/org/python/antlr/ast/AugAssign.java branches/newstyle-java-types/src/org/python/antlr/ast/BinOp.java branches/newstyle-java-types/src/org/python/antlr/ast/BoolOp.java branches/newstyle-java-types/src/org/python/antlr/ast/Break.java branches/newstyle-java-types/src/org/python/antlr/ast/Call.java branches/newstyle-java-types/src/org/python/antlr/ast/ClassDef.java branches/newstyle-java-types/src/org/python/antlr/ast/Compare.java branches/newstyle-java-types/src/org/python/antlr/ast/Continue.java branches/newstyle-java-types/src/org/python/antlr/ast/Delete.java branches/newstyle-java-types/src/org/python/antlr/ast/Dict.java branches/newstyle-java-types/src/org/python/antlr/ast/Ellipsis.java branches/newstyle-java-types/src/org/python/antlr/ast/ErrorExpr.java branches/newstyle-java-types/src/org/python/antlr/ast/ErrorMod.java branches/newstyle-java-types/src/org/python/antlr/ast/ErrorSlice.java branches/newstyle-java-types/src/org/python/antlr/ast/ErrorStmt.java branches/newstyle-java-types/src/org/python/antlr/ast/Exec.java branches/newstyle-java-types/src/org/python/antlr/ast/Expr.java branches/newstyle-java-types/src/org/python/antlr/ast/Expression.java branches/newstyle-java-types/src/org/python/antlr/ast/ExtSlice.java branches/newstyle-java-types/src/org/python/antlr/ast/For.java branches/newstyle-java-types/src/org/python/antlr/ast/FunctionDef.java branches/newstyle-java-types/src/org/python/antlr/ast/GeneratorExp.java branches/newstyle-java-types/src/org/python/antlr/ast/Global.java branches/newstyle-java-types/src/org/python/antlr/ast/If.java branches/newstyle-java-types/src/org/python/antlr/ast/IfExp.java branches/newstyle-java-types/src/org/python/antlr/ast/Import.java branches/newstyle-java-types/src/org/python/antlr/ast/ImportFrom.java branches/newstyle-java-types/src/org/python/antlr/ast/Index.java branches/newstyle-java-types/src/org/python/antlr/ast/Interactive.java branches/newstyle-java-types/src/org/python/antlr/ast/Lambda.java branches/newstyle-java-types/src/org/python/antlr/ast/List.java branches/newstyle-java-types/src/org/python/antlr/ast/ListComp.java branches/newstyle-java-types/src/org/python/antlr/ast/Module.java branches/newstyle-java-types/src/org/python/antlr/ast/Name.java branches/newstyle-java-types/src/org/python/antlr/ast/Num.java branches/newstyle-java-types/src/org/python/antlr/ast/Pass.java branches/newstyle-java-types/src/org/python/antlr/ast/Print.java branches/newstyle-java-types/src/org/python/antlr/ast/Raise.java branches/newstyle-java-types/src/org/python/antlr/ast/Repr.java branches/newstyle-java-types/src/org/python/antlr/ast/Return.java branches/newstyle-java-types/src/org/python/antlr/ast/Slice.java branches/newstyle-java-types/src/org/python/antlr/ast/Str.java branches/newstyle-java-types/src/org/python/antlr/ast/Subscript.java branches/newstyle-java-types/src/org/python/antlr/ast/Suite.java branches/newstyle-java-types/src/org/python/antlr/ast/TryExcept.java branches/newstyle-java-types/src/org/python/antlr/ast/TryFinally.java branches/newstyle-java-types/src/org/python/antlr/ast/Tuple.java branches/newstyle-java-types/src/org/python/antlr/ast/UnaryOp.java branches/newstyle-java-types/src/org/python/antlr/ast/While.java branches/newstyle-java-types/src/org/python/antlr/ast/With.java branches/newstyle-java-types/src/org/python/antlr/ast/Yield.java branches/newstyle-java-types/src/org/python/antlr/ast/aliasType.java branches/newstyle-java-types/src/org/python/antlr/ast/argumentsType.java branches/newstyle-java-types/src/org/python/antlr/ast/boolopType.java branches/newstyle-java-types/src/org/python/antlr/ast/cmpopType.java branches/newstyle-java-types/src/org/python/antlr/ast/comprehensionType.java branches/newstyle-java-types/src/org/python/antlr/ast/excepthandlerType.java branches/newstyle-java-types/src/org/python/antlr/ast/exprType.java branches/newstyle-java-types/src/org/python/antlr/ast/expr_contextType.java branches/newstyle-java-types/src/org/python/antlr/ast/keywordType.java branches/newstyle-java-types/src/org/python/antlr/ast/modType.java branches/newstyle-java-types/src/org/python/antlr/ast/operatorType.java branches/newstyle-java-types/src/org/python/antlr/ast/sliceType.java branches/newstyle-java-types/src/org/python/antlr/ast/stmtType.java branches/newstyle-java-types/src/org/python/antlr/ast/unaryopType.java branches/newstyle-java-types/src/org/python/compiler/CodeCompiler.java branches/newstyle-java-types/src/org/python/compiler/Module.java branches/newstyle-java-types/src/org/python/compiler/ScopesCompiler.java branches/newstyle-java-types/src/org/python/core/Py.java branches/newstyle-java-types/src/org/python/core/PyArray.java branches/newstyle-java-types/src/org/python/core/PyBoolean.java branches/newstyle-java-types/src/org/python/core/PyBuiltinCallable.java branches/newstyle-java-types/src/org/python/core/PyCell.java branches/newstyle-java-types/src/org/python/core/PyClassMethodDescr.java branches/newstyle-java-types/src/org/python/core/PyDataDescr.java branches/newstyle-java-types/src/org/python/core/PyDictProxy.java branches/newstyle-java-types/src/org/python/core/PyEllipsis.java branches/newstyle-java-types/src/org/python/core/PyFile.java branches/newstyle-java-types/src/org/python/core/PyFunction.java branches/newstyle-java-types/src/org/python/core/PyGenerator.java branches/newstyle-java-types/src/org/python/core/PyMethod.java branches/newstyle-java-types/src/org/python/core/PyMethodDescr.java branches/newstyle-java-types/src/org/python/core/PyNone.java branches/newstyle-java-types/src/org/python/core/PyNotImplemented.java branches/newstyle-java-types/src/org/python/core/PyObject.java branches/newstyle-java-types/src/org/python/core/PySequence.java branches/newstyle-java-types/src/org/python/core/PySlice.java branches/newstyle-java-types/src/org/python/core/PySlot.java branches/newstyle-java-types/src/org/python/core/PyString.java branches/newstyle-java-types/src/org/python/core/PySystemState.java branches/newstyle-java-types/src/org/python/core/PyTraceback.java branches/newstyle-java-types/src/org/python/core/PyType.java branches/newstyle-java-types/src/org/python/core/PyXRange.java branches/newstyle-java-types/src/org/python/core/__builtin__.java branches/newstyle-java-types/src/org/python/core/imp.java branches/newstyle-java-types/src/org/python/core/io/FileIO.java branches/newstyle-java-types/src/org/python/core/io/IOBase.java branches/newstyle-java-types/src/org/python/core/io/ServerSocketIO.java branches/newstyle-java-types/src/org/python/core/util/FileUtil.java branches/newstyle-java-types/src/org/python/expose/BaseTypeBuilder.java branches/newstyle-java-types/src/org/python/expose/ExposedType.java branches/newstyle-java-types/src/org/python/expose/TypeBuilder.java branches/newstyle-java-types/src/org/python/expose/generate/DescriptorExposer.java branches/newstyle-java-types/src/org/python/expose/generate/ExposedTypeProcessor.java branches/newstyle-java-types/src/org/python/expose/generate/ExposedTypeVisitor.java branches/newstyle-java-types/src/org/python/expose/generate/Exposer.java branches/newstyle-java-types/src/org/python/expose/generate/InstanceMethodExposer.java branches/newstyle-java-types/src/org/python/expose/generate/TypeExposer.java branches/newstyle-java-types/src/org/python/modules/PyTeeIterator.java branches/newstyle-java-types/src/org/python/modules/_codecs.java branches/newstyle-java-types/src/org/python/modules/_py_compile.java branches/newstyle-java-types/src/org/python/modules/_weakref/CallableProxyType.java branches/newstyle-java-types/src/org/python/modules/_weakref/ProxyType.java branches/newstyle-java-types/src/org/python/modules/errno.java branches/newstyle-java-types/src/org/python/modules/imp.java branches/newstyle-java-types/src/org/python/modules/itertools.java branches/newstyle-java-types/src/org/python/modules/operator.java branches/newstyle-java-types/src/org/python/modules/struct.java branches/newstyle-java-types/src/org/python/modules/thread/thread.java branches/newstyle-java-types/src/org/python/modules/time/PyTimeTuple.java branches/newstyle-java-types/src/org/python/modules/time/Time.java branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporter.java branches/newstyle-java-types/src/shell/jython branches/newstyle-java-types/src/shell/jython.bat branches/newstyle-java-types/tests/java/org/python/expose/generate/DescriptorExposerTest.java branches/newstyle-java-types/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java branches/newstyle-java-types/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java branches/newstyle-java-types/tests/java/org/python/expose/generate/MethodExposerTest.java branches/newstyle-java-types/tests/java/org/python/expose/generate/SimpleExposed.java branches/newstyle-java-types/tests/java/org/python/expose/generate/TypeExposerTest.java Added Paths: ----------- branches/newstyle-java-types/Lib/pydoc.py branches/newstyle-java-types/Lib/test/test_genexps_jy.py branches/newstyle-java-types/Lib/test/test_zipfile.py branches/newstyle-java-types/Lib/warnings.py branches/newstyle-java-types/Lib/zipfile.py branches/newstyle-java-types/extlibs/antlr-3.1.1-runtime.jar branches/newstyle-java-types/extlibs/antlr-3.1.1.jar branches/newstyle-java-types/extlibs/constantine-0.4.jar branches/newstyle-java-types/tests/java/org/python/util/ branches/newstyle-java-types/tests/java/org/python/util/InterpreterTest.java Removed Paths: ------------- branches/newstyle-java-types/extlibs/antlr-3.1.jar branches/newstyle-java-types/extlibs/antlr-runtime-3.1.jar branches/newstyle-java-types/tests/java/org/python/util/InterpreterTest.java Property Changed: ---------------- branches/newstyle-java-types/ Property changes on: branches/newstyle-java-types ___________________________________________________________________ Modified: svnmerge-integrated - /branches/nowalker:1-5263 /trunk/jython:1-5562 + /branches/nowalker:1-5263 /trunk/jython:1-5664 Added: svn:mergeinfo + /trunk/jython:5565-5661 Modified: branches/newstyle-java-types/.classpath =================================================================== --- branches/newstyle-java-types/.classpath 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/.classpath 2008-12-01 00:38:14 UTC (rev 5665) @@ -14,6 +14,6 @@ <classpathentry kind="lib" path="extlibs/servlet-api-2.5.jar"/> <classpathentry kind="lib" path="build/jarjar"/> <classpathentry kind="var" path="ANT_HOME/lib/ant.jar"/> - <classpathentry kind="lib" path="extlibs/antlr-runtime-3.1.jar"/> + <classpathentry kind="lib" path="extlibs/antlr-3.1.1-runtime.jar"/> <classpathentry kind="output" path="bugtests/classes"/> </classpath> Modified: branches/newstyle-java-types/Lib/datetime.py =================================================================== --- branches/newstyle-java-types/Lib/datetime.py 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/Lib/datetime.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -1574,7 +1574,7 @@ # Convert self to UTC, and attach the new time zone object. myoffset = self.utcoffset() if myoffset is None: - raise ValuError("astimezone() requires an aware datetime") + raise ValueError("astimezone() requires an aware datetime") utc = (self - myoffset).replace(tzinfo=tz) # Convert from UTC to tz's local time. Modified: branches/newstyle-java-types/Lib/inspect.py =================================================================== --- branches/newstyle-java-types/Lib/inspect.py 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/Lib/inspect.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -383,6 +383,8 @@ filename = getfile(object) if string.lower(filename[-4:]) in ('.pyc', '.pyo'): filename = filename[:-4] + '.py' + elif filename.endswith('$py.class'): + filename = filename[:-9] + '.py' for suffix, mode, kind in imp.get_suffixes(): if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: # Looks like a binary file. We want to only return a text file. Modified: branches/newstyle-java-types/Lib/ntpath.py =================================================================== --- branches/newstyle-java-types/Lib/ntpath.py 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/Lib/ntpath.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -9,6 +9,7 @@ import os import stat import sys +from org.python.core.Py import newString __all__ = ["normcase","isabs","join","splitdrive","split","splitext", "basename","dirname","commonprefix","getsize","getmtime", @@ -493,7 +494,8 @@ if not splitunc(path)[0] and not splitdrive(path)[0]: # cwd lacks a UNC mount point, so it should have a drive # letter (but lacks one): determine it - drive = splitdrive(java.io.File(path).getCanonicalPath())[0] + canon_path = newString(java.io.File(path).getCanonicalPath()) + drive = splitdrive(canon_path)[0] path = join(drive, path) return normpath(path) Modified: branches/newstyle-java-types/Lib/os.py =================================================================== --- branches/newstyle-java-types/Lib/os.py 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/Lib/os.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -46,6 +46,7 @@ import stat as _stat import sys from java.io import File +from org.python.constantine.platform import Errno from org.python.core.io import FileDescriptors, FileIO, IOBase from org.python.core.Py import newString as asPyString @@ -101,7 +102,7 @@ err = getattr(errno, error.name(), None) if err is None: raise OSError('%s: %s' % (error, msg)) - raise OSError(err, errno.strerror(err), msg) + raise OSError(err, strerror(err), msg) def unimplementedError(self, method_name): raise NotImplementedError(method_name) def warn(self, warning_id, msg, rest): @@ -237,7 +238,7 @@ Return a string representing the current working directory. """ - return sys.getCurrentWorkingDir() + return asPyString(sys.getCurrentWorkingDir()) def chdir(path): """chdir(path) @@ -246,9 +247,9 @@ """ realpath = _path.realpath(path) if not _path.exists(realpath): - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) if not _path.isdir(realpath): - raise OSError(errno.ENOTDIR, errno.strerror(errno.ENOTDIR), path) + raise OSError(errno.ENOTDIR, strerror(errno.ENOTDIR), path) sys.setCurrentWorkingDir(realpath) def listdir(path): @@ -275,7 +276,7 @@ # catch not found errors explicitly here, for now abs_path = sys.getPath(path) if not File(abs_path).exists(): - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) _posix.chmod(abs_path, mode) def mkdir(path, mode='ignored'): @@ -292,7 +293,7 @@ err = errno.EEXIST else: err = 0 - msg = errno.strerror(err) if err else "couldn't make directory" + msg = strerror(err) if err else "couldn't make directory" raise OSError(err, msg, path) def makedirs(path, mode='ignored'): @@ -371,9 +372,9 @@ Remove a directory.""" f = File(sys.getPath(path)) if not f.exists(): - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) elif not f.isDirectory(): - raise OSError(errno.ENOTDIR, errno.strerror(errno.ENOTDIR), path) + raise OSError(errno.ENOTDIR, strerror(errno.ENOTDIR), path) elif not f.delete(): raise OSError(0, "couldn't delete directory", path) @@ -409,10 +410,17 @@ """ if not isinstance(code, (int, long)): raise TypeError('an integer is required') - try: - return errno.strerror(code) - except KeyError: + constant = Errno.valueOf(code) + if constant is Errno.__UNKNOWN_CONSTANT__: return 'Unknown error: %d' % code + if constant.name() == constant.description(): + # XXX: have constantine handle this fallback + # Fake constant or just lacks a description, fallback to Linux's + from org.python.constantine.platform.linux import Errno as LinuxErrno + constant = getattr(LinuxErrno, constant.name(), None) + if not constant: + return 'Unknown error: %d' % code + return asPyString(constant.toString()) def access(path, mode): """access(path, mode) -> True if granted, False otherwise @@ -459,7 +467,7 @@ raise f = File(abs_path) if not f.exists(): - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) size = f.length() mtime = f.lastModified() / 1000.0 mode = 0 @@ -509,7 +517,7 @@ # Not a link, only now can we determine if it exists (because # File.exists() returns False for dead links) if not f.exists(): - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) return stat(path) def utime(path, times): @@ -550,12 +558,12 @@ if (len(mode) and mode[0] or '') not in 'rwa': raise ValueError("invalid file mode '%s'" % mode) if rawio.closed(): - raise OSError(errno.EBADF, errno.strerror(errno.EBADF)) + raise OSError(errno.EBADF, strerror(errno.EBADF)) try: fp = FileDescriptors.wrap(rawio, mode, bufsize) except IOError: - raise OSError(errno.EINVAL, errno.strerror(errno.EINVAL)) + raise OSError(errno.EINVAL, strerror(errno.EINVAL)) return fp def ftruncate(fd, length): @@ -567,7 +575,7 @@ try: rawio.truncate(length) except Exception, e: - raise IOError(errno.EBADF, errno.strerror(errno.EBADF)) + raise IOError(errno.EBADF, strerror(errno.EBADF)) def lseek(fd, pos, how): """lseek(fd, pos, how) -> newpos @@ -593,10 +601,10 @@ appending = flag & O_APPEND if updating and writing: - raise OSError(errno.EINVAL, errno.strerror(errno.EINVAL), filename) + raise OSError(errno.EINVAL, strerror(errno.EINVAL), filename) if not creating and not path.exists(filename): - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), filename) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), filename) if not writing: if updating: @@ -611,7 +619,7 @@ if exclusive and creating: try: if not File(sys.getPath(filename)).createNewFile(): - raise OSError(errno.EEXIST, errno.strerror(errno.EEXIST), + raise OSError(errno.EEXIST, strerror(errno.EEXIST), filename) except java.io.IOException, ioe: raise OSError(ioe) @@ -627,8 +635,8 @@ fchannel = RandomAccessFile(sys.getPath(filename), 'rws').getChannel() except FileNotFoundException, fnfe: if path.isdir(filename): - raise OSError(errno.EISDIR, errno.strerror(errno.EISDIR)) - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), filename) + raise OSError(errno.EISDIR, strerror(errno.EISDIR)) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), filename) return FileIO(fchannel, mode) return FileIO(filename, mode) @@ -659,7 +667,7 @@ try: return func(*args, **kwargs) except: - raise OSError(errno.EBADF, errno.strerror(errno.EBADF)) + raise OSError(errno.EBADF, strerror(errno.EBADF)) if _name == 'posix' and _native_posix: def link(src, dst): Modified: branches/newstyle-java-types/Lib/popen2.py =================================================================== --- branches/newstyle-java-types/Lib/popen2.py 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/Lib/popen2.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -44,7 +44,7 @@ the close method. """ def __init__(self, stream, process, name): - self._file = FileUtil.wrap(stream) + self._file = FileUtil.wrap(stream, 0) self._process = process def __getattr__(self, name): @@ -93,10 +93,10 @@ bufsize ) - self.tochild = FileUtil.wrap(self._tochild) - self.fromchild = FileUtil.wrap(self._fromchild) + self.tochild = FileUtil.wrap(self._tochild, 0) + self.fromchild = FileUtil.wrap(self._fromchild, 0) if self._childerr: - self.childerr = FileUtil.wrap(self._childerr) + self.childerr = FileUtil.wrap(self._childerr, 0) def _startChildWaiter(self): """Start a subthread that waits for the child process to exit.""" @@ -198,7 +198,7 @@ "%s-stderr" % self.process, self._close ) - return FileUtil.wrap(joinedStream) + return FileUtil.wrap(joinedStream, 0) def _close( self ): """Must be closed twice (once for each of the two joined pipes)""" Modified: branches/newstyle-java-types/Lib/posixpath.py =================================================================== --- branches/newstyle-java-types/Lib/posixpath.py 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/Lib/posixpath.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -14,6 +14,7 @@ import java.io.IOException import os import stat +from org.python.core.Py import newString __all__ = ["normcase","isabs","join","splitdrive","split","splitext", "basename","dirname","commonprefix","getsize","getmtime", @@ -218,8 +219,8 @@ if not os._native_posix: def samefile(f1, f2): """Test whether two pathnames reference the same actual file""" - canon1 = java.io.File(_ensure_str(f1)).getCanonicalPath() - canon2 = java.io.File(_ensure_str(f2)).getCanonicalPath() + canon1 = newString(java.io.File(_ensure_str(f1)).getCanonicalPath()) + canon2 = newString(java.io.File(_ensure_str(f2)).getCanonicalPath()) return canon1 == canon2 else: def samefile(f1, f2): @@ -240,7 +241,7 @@ s2 = os.fstat(fp2) return samestat(s1, s2) - __all__append("sameopenfile") + __all__.append("sameopenfile") if os._native_posix: @@ -448,7 +449,7 @@ encounter a path we've seen before (meaning that there's a loop). """ try: - return str(java.io.File(abspath(path)).getCanonicalPath()) + return newString(java.io.File(abspath(path)).getCanonicalPath()) except java.io.IOException: return None else: Copied: branches/newstyle-java-types/Lib/pydoc.py (from rev 5661, trunk/jython/Lib/pydoc.py) =================================================================== --- branches/newstyle-java-types/Lib/pydoc.py (rev 0) +++ branches/newstyle-java-types/Lib/pydoc.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -0,0 +1,2257 @@ +#!/usr/bin/env python +# -*- coding: Latin-1 -*- +"""Generate Python documentation in HTML or text for interactive use. + +In the Python interpreter, do "from pydoc import help" to provide online +help. Calling help(thing) on a Python object documents the object. + +Or, at the shell command line outside of Python: + +Run "pydoc <name>" to show documentation on something. <name> may be +the name of a function, module, package, or a dotted reference to a +class or function within a module or module in a package. If the +argument contains a path segment delimiter (e.g. slash on Unix, +backslash on Windows) it is treated as the path to a Python source file. + +Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines +of all available modules. + +Run "pydoc -p <port>" to start an HTTP server on a given port on the +local machine to generate documentation web pages. + +For platforms without a command line, "pydoc -g" starts the HTTP server +and also pops up a little window for controlling it. + +Run "pydoc -w <name>" to write out the HTML documentation for a module +to a file named "<name>.html". + +Module docs for core modules are assumed to be in + + http://www.python.org/doc/current/lib/ + +This can be overridden by setting the PYTHONDOCS environment variable +to a different URL or to a local directory containing the Library +Reference Manual pages. +""" + +__author__ = "Ka-Ping Yee <pi...@lf...>" +__date__ = "26 February 2001" + +__version__ = "$Revision: 54366 $" +__credits__ = """Guido van Rossum, for an excellent programming language. +Tommy Burnette, the original creator of manpy. +Paul Prescod, for all his work on onlinehelp. +Richard Chamberlain, for the first implementation of textdoc. +""" + +# Known bugs that can't be fixed here: +# - imp.load_module() cannot be prevented from clobbering existing +# loaded modules, so calling synopsis() on a binary module file +# changes the contents of any existing module with the same name. +# - If the __file__ attribute on a module is a relative path and +# the current directory is changed with os.chdir(), an incorrect +# path will be displayed. + +import sys, imp, os, re, types, inspect, __builtin__, pkgutil +from repr import Repr +from string import expandtabs, find, join, lower, split, strip, rfind, rstrip +try: + from collections import deque +except ImportError: + # Python 2.3 compatibility + class deque(list): + def popleft(self): + return self.pop(0) + +# --------------------------------------------------------- common routines + +def pathdirs(): + """Convert sys.path into a list of absolute, existing, unique paths.""" + dirs = [] + normdirs = [] + for dir in sys.path: + dir = os.path.abspath(dir or '.') + normdir = os.path.normcase(dir) + if normdir not in normdirs and os.path.isdir(dir): + dirs.append(dir) + normdirs.append(normdir) + return dirs + +def getdoc(object): + """Get the doc string or comments for an object.""" + result = inspect.getdoc(object) or inspect.getcomments(object) + return result and re.sub('^ *\n', '', rstrip(result)) or '' + +def splitdoc(doc): + """Split a doc string into a synopsis line (if any) and the rest.""" + lines = split(strip(doc), '\n') + if len(lines) == 1: + return lines[0], '' + elif len(lines) >= 2 and not rstrip(lines[1]): + return lines[0], join(lines[2:], '\n') + return '', join(lines, '\n') + +def classname(object, modname): + """Get a class name and qualify it with a module name if necessary.""" + name = object.__name__ + if object.__module__ != modname: + name = object.__module__ + '.' + name + return name + +def isdata(object): + """Check if an object is of a type that probably means it's data.""" + return not (inspect.ismodule(object) or inspect.isclass(object) or + inspect.isroutine(object) or inspect.isframe(object) or + inspect.istraceback(object) or inspect.iscode(object)) + +def replace(text, *pairs): + """Do a series of global replacements on a string.""" + while pairs: + text = join(split(text, pairs[0]), pairs[1]) + pairs = pairs[2:] + return text + +def cram(text, maxlen): + """Omit part of a string if needed to make it fit in a maximum length.""" + if len(text) > maxlen: + pre = max(0, (maxlen-3)//2) + post = max(0, maxlen-3-pre) + return text[:pre] + '...' + text[len(text)-post:] + return text + +_re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE) +def stripid(text): + """Remove the hexadecimal id from a Python object representation.""" + # The behaviour of %p is implementation-dependent in terms of case. + if _re_stripid.search(repr(Exception)): + return _re_stripid.sub(r'\1', text) + return text + +def _is_some_method(obj): + return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) + +def allmethods(cl): + methods = {} + for key, value in inspect.getmembers(cl, _is_some_method): + methods[key] = 1 + for base in cl.__bases__: + methods.update(allmethods(base)) # all your base are belong to us + for key in methods.keys(): + methods[key] = getattr(cl, key) + return methods + +def _split_list(s, predicate): + """Split sequence s via predicate, and return pair ([true], [false]). + + The return value is a 2-tuple of lists, + ([x for x in s if predicate(x)], + [x for x in s if not predicate(x)]) + """ + + yes = [] + no = [] + for x in s: + if predicate(x): + yes.append(x) + else: + no.append(x) + return yes, no + +def visiblename(name, all=None): + """Decide whether to show documentation on a variable.""" + # Certain special names are redundant. + if name in ('__builtins__', '__doc__', '__file__', '__path__', + '__module__', '__name__', '__slots__'): return 0 + # Private names are hidden, but special names are displayed. + if name.startswith('__') and name.endswith('__'): return 1 + if all is not None: + # only document that which the programmer exported in __all__ + return name in all + else: + return not name.startswith('_') + +def classify_class_attrs(object): + """Wrap inspect.classify_class_attrs, with fixup for data descriptors.""" + def fixup((name, kind, cls, value)): + if inspect.isdatadescriptor(value): + kind = 'data descriptor' + return name, kind, cls, value + return map(fixup, inspect.classify_class_attrs(object)) + +# ----------------------------------------------------- module manipulation + +def ispackage(path): + """Guess whether a path refers to a package directory.""" + if os.path.isdir(path): + for ext in ('.py', '.pyc', '.pyo', '$py.class'): + if os.path.isfile(os.path.join(path, '__init__' + ext)): + return True + return False + +def source_synopsis(file): + line = file.readline() + while line[:1] == '#' or not strip(line): + line = file.readline() + if not line: break + line = strip(line) + if line[:4] == 'r"""': line = line[1:] + if line[:3] == '"""': + line = line[3:] + if line[-1:] == '\\': line = line[:-1] + while not strip(line): + line = file.readline() + if not line: break + result = strip(split(line, '"""')[0]) + else: result = None + return result + +def synopsis(filename, cache={}): + """Get the one-line summary out of a module file.""" + mtime = os.stat(filename).st_mtime + lastupdate, result = cache.get(filename, (0, None)) + if lastupdate < mtime: + info = inspect.getmoduleinfo(filename) + try: + file = open(filename) + except IOError: + # module can't be opened, so skip it + return None + if info and 'b' in info[2]: # binary modules have to be imported + try: module = imp.load_module('__temp__', file, filename, info[1:]) + except: return None + result = (module.__doc__ or '').splitlines()[0] + del sys.modules['__temp__'] + else: # text modules can be directly examined + result = source_synopsis(file) + file.close() + cache[filename] = (mtime, result) + return result + +class ErrorDuringImport(Exception): + """Errors that occurred while trying to import something to document it.""" + def __init__(self, filename, (exc, value, tb)): + self.filename = filename + self.exc = exc + self.value = value + self.tb = tb + + def __str__(self): + exc = self.exc + if type(exc) is types.ClassType: + exc = exc.__name__ + return 'problem in %s - %s: %s' % (self.filename, exc, self.value) + +def importfile(path): + """Import a Python source file or compiled file given its path.""" + magic = imp.get_magic() + file = open(path, 'r') + if file.read(len(magic)) == magic: + kind = imp.PY_COMPILED + else: + kind = imp.PY_SOURCE + file.close() + filename = os.path.basename(path) + name, ext = os.path.splitext(filename) + file = open(path, 'r') + try: + module = imp.load_module(name, file, path, (ext, 'r', kind)) + except: + raise ErrorDuringImport(path, sys.exc_info()) + file.close() + return module + +def safeimport(path, forceload=0, cache={}): + """Import a module; handle errors; return None if the module isn't found. + + If the module *is* found but an exception occurs, it's wrapped in an + ErrorDuringImport exception and reraised. Unlike __import__, if a + package path is specified, the module at the end of the path is returned, + not the package at the beginning. If the optional 'forceload' argument + is 1, we reload the module from disk (unless it's a dynamic extension).""" + try: + # If forceload is 1 and the module has been previously loaded from + # disk, we always have to reload the module. Checking the file's + # mtime isn't good enough (e.g. the module could contain a class + # that inherits from another module that has changed). + if forceload and path in sys.modules: + if path not in sys.builtin_module_names: + # Avoid simply calling reload() because it leaves names in + # the currently loaded module lying around if they're not + # defined in the new source file. Instead, remove the + # module from sys.modules and re-import. Also remove any + # submodules because they won't appear in the newly loaded + # module's namespace if they're already in sys.modules. + subs = [m for m in sys.modules if m.startswith(path + '.')] + for key in [path] + subs: + # Prevent garbage collection. + cache[key] = sys.modules[key] + del sys.modules[key] + module = __import__(path) + except: + # Did the error occur before or after the module was found? + (exc, value, tb) = info = sys.exc_info() + if path in sys.modules: + # An error occurred while executing the imported module. + raise ErrorDuringImport(sys.modules[path].__file__, info) + elif exc is SyntaxError: + # A SyntaxError occurred before we could execute the module. + raise ErrorDuringImport(value.filename, info) + elif exc is ImportError and \ + split(lower(str(value)))[:2] == ['no', 'module']: + # The module was not found. + return None + else: + # Some other error occurred during the importing process. + raise ErrorDuringImport(path, sys.exc_info()) + for part in split(path, '.')[1:]: + try: module = getattr(module, part) + except AttributeError: return None + return module + +# ---------------------------------------------------- formatter base class + +class Doc: + def document(self, object, name=None, *args): + """Generate documentation for an object.""" + args = (object, name) + args + # 'try' clause is to attempt to handle the possibility that inspect + # identifies something in a way that pydoc itself has issues handling; + # think 'super' and how it is a descriptor (which raises the exception + # by lacking a __name__ attribute) and an instance. + if inspect.isgetsetdescriptor(object): return self.docdata(*args) + if inspect.ismemberdescriptor(object): return self.docdata(*args) + try: + if inspect.ismodule(object): return self.docmodule(*args) + if inspect.isclass(object): return self.docclass(*args) + if inspect.isroutine(object): return self.docroutine(*args) + except AttributeError: + pass + if isinstance(object, property): return self.docproperty(*args) + return self.docother(*args) + + def fail(self, object, name=None, *args): + """Raise an exception for unimplemented types.""" + message = "don't know how to document object%s of type %s" % ( + name and ' ' + repr(name), type(object).__name__) + raise TypeError, message + + docmodule = docclass = docroutine = docother = docproperty = docdata = fail + + def getdocloc(self, object): + """Return the location of module docs or None""" + + try: + file = inspect.getabsfile(object) + except TypeError: + file = '(built-in)' + + docloc = os.environ.get("PYTHONDOCS", + "http://www.python.org/doc/current/lib") + basedir = os.path.join(sys.exec_prefix, "lib", + "python"+sys.version[0:3]) + if (isinstance(object, type(os)) and + (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', + 'marshal', 'posix', 'signal', 'sys', + 'thread', 'zipimport') or + (file.startswith(basedir) and + not file.startswith(os.path.join(basedir, 'site-packages'))))): + htmlfile = "module-%s.html" % object.__name__ + if docloc.startswith("http://"): + docloc = "%s/%s" % (docloc.rstrip("/"), htmlfile) + else: + docloc = os.path.join(docloc, htmlfile) + else: + docloc = None + return docloc + +# -------------------------------------------- HTML documentation generator + +class HTMLRepr(Repr): + """Class for safely making an HTML representation of a Python object.""" + def __init__(self): + Repr.__init__(self) + self.maxlist = self.maxtuple = 20 + self.maxdict = 10 + self.maxstring = self.maxother = 100 + + def escape(self, text): + return replace(text, '&', '&', '<', '<', '>', '>') + + def repr(self, object): + return Repr.repr(self, object) + + def repr1(self, x, level): + if hasattr(type(x), '__name__'): + methodname = 'repr_' + join(split(type(x).__name__), '_') + if hasattr(self, methodname): + return getattr(self, methodname)(x, level) + return self.escape(cram(stripid(repr(x)), self.maxother)) + + def repr_string(self, x, level): + test = cram(x, self.maxstring) + testrepr = repr(test) + if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): + # Backslashes are only literal in the string and are never + # needed to make any special characters, so show a raw string. + return 'r' + testrepr[0] + self.escape(test) + testrepr[0] + return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)', + r'<font color="#c040c0">\1</font>', + self.escape(testrepr)) + + repr_str = repr_string + + def repr_instance(self, x, level): + try: + return self.escape(cram(stripid(repr(x)), self.maxstring)) + except: + return self.escape('<%s instance>' % x.__class__.__name__) + + repr_unicode = repr_string + +class HTMLDoc(Doc): + """Formatter class for HTML documentation.""" + + # ------------------------------------------- HTML formatting utilities + + _repr_instance = HTMLRepr() + repr = _repr_instance.repr + escape = _repr_instance.escape + + def page(self, title, contents): + """Format an HTML page.""" + return ''' +<!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> +<html><head><title>Python: %s</title> +</head><body bgcolor="#f0f0f8"> +%s +</body></html>''' % (title, contents) + + def heading(self, title, fgcol, bgcol, extras=''): + """Format a page heading.""" + return ''' +<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading"> +<tr bgcolor="%s"> +<td valign=bottom> <br> +<font color="%s" face="helvetica, arial"> <br>%s</font></td +><td align=right valign=bottom +><font color="%s" face="helvetica, arial">%s</font></td></tr></table> + ''' % (bgcol, fgcol, title, fgcol, extras or ' ') + + def section(self, title, fgcol, bgcol, contents, width=6, + prelude='', marginalia=None, gap=' '): + """Format a section with a heading.""" + if marginalia is None: + marginalia = '<tt>' + ' ' * width + '</tt>' + result = '''<p> +<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> +<tr bgcolor="%s"> +<td colspan=3 valign=bottom> <br> +<font color="%s" face="helvetica, arial">%s</font></td></tr> + ''' % (bgcol, fgcol, title) + if prelude: + result = result + ''' +<tr bgcolor="%s"><td rowspan=2>%s</td> +<td colspan=2>%s</td></tr> +<tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap) + else: + result = result + ''' +<tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap) + + return result + '\n<td width="100%%">%s</td></tr></table>' % contents + + def bigsection(self, title, *args): + """Format a section with a big heading.""" + title = '<big><strong>%s</strong></big>' % title + return self.section(title, *args) + + def preformat(self, text): + """Format literal preformatted text.""" + text = self.escape(expandtabs(text)) + return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', + ' ', ' ', '\n', '<br>\n') + + def multicolumn(self, list, format, cols=4): + """Format a list of items into a multi-column list.""" + result = '' + rows = (len(list)+cols-1)/cols + for col in range(cols): + result = result + '<td width="%d%%" valign=top>' % (100/cols) + for i in range(rows*col, rows*col+rows): + if i < len(list): + result = result + format(list[i]) + '<br>\n' + result = result + '</td>' + return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result + + def grey(self, text): return '<font color="#909090">%s</font>' % text + + def namelink(self, name, *dicts): + """Make a link for an identifier, given name-to-URL mappings.""" + for dict in dicts: + if name in dict: + return '<a href="%s">%s</a>' % (dict[name], name) + return name + + def classlink(self, object, modname): + """Make a link for a class.""" + name, module = object.__name__, sys.modules.get(object.__module__) + if hasattr(module, name) and getattr(module, name) is object: + return '<a href="%s.html#%s">%s</a>' % ( + module.__name__, name, classname(object, modname)) + return classname(object, modname) + + def modulelink(self, object): + """Make a link for a module.""" + return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__) + + def modpkglink(self, (name, path, ispackage, shadowed)): + """Make a link for a module or package to display in an index.""" + if shadowed: + return self.grey(name) + if path: + url = '%s.%s.html' % (path, name) + else: + url = '%s.html' % name + if ispackage: + text = '<strong>%s</strong> (package)' % name + else: + text = name + return '<a href="%s">%s</a>' % (url, text) + + def markup(self, text, escape=None, funcs={}, classes={}, methods={}): + """Mark up some plain text, given a context of symbols to look for. + Each context dictionary maps object names to anchor names.""" + escape = escape or self.escape + results = [] + here = 0 + pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' + r'RFC[- ]?(\d+)|' + r'PEP[- ]?(\d+)|' + r'(self\.)?(\w+))') + while True: + match = pattern.search(text, here) + if not match: break + start, end = match.span() + results.append(escape(text[here:start])) + + all, scheme, rfc, pep, selfdot, name = match.groups() + if scheme: + url = escape(all).replace('"', '"') + results.append('<a href="%s">%s</a>' % (url, url)) + elif rfc: + url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) + results.append('<a href="%s">%s</a>' % (url, escape(all))) + elif pep: + url = 'http://www.python.org/peps/pep-%04d.html' % int(pep) + results.append('<a href="%s">%s</a>' % (url, escape(all))) + elif text[end:end+1] == '(': + results.append(self.namelink(name, methods, funcs, classes)) + elif selfdot: + results.append('self.<strong>%s</strong>' % name) + else: + results.append(self.namelink(name, classes)) + here = end + results.append(escape(text[here:])) + return join(results, '') + + # ---------------------------------------------- type-specific routines + + def formattree(self, tree, modname, parent=None): + """Produce HTML for a class tree as given by inspect.getclasstree().""" + result = '' + for entry in tree: + if type(entry) is type(()): + c, bases = entry + result = result + '<dt><font face="helvetica, arial">' + result = result + self.classlink(c, modname) + if bases and bases != (parent,): + parents = [] + for base in bases: + parents.append(self.classlink(base, modname)) + result = result + '(' + join(parents, ', ') + ')' + result = result + '\n</font></dt>' +... [truncated message content] |
From: <cg...@us...> - 2008-11-30 05:37:16
|
Revision: 5664 http://jython.svn.sourceforge.net/jython/?rev=5664&view=rev Author: cgroves Date: 2008-11-30 05:37:11 +0000 (Sun, 30 Nov 2008) Log Message: ----------- Initialized merge tracking via "svnmerge" with revisions "1-5562" from https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython Property Changed: ---------------- branches/newstyle-java-types/ Property changes on: branches/newstyle-java-types ___________________________________________________________________ Modified: svnmerge-integrated - /branches/nowalker:1-5263 + /branches/nowalker:1-5263 /trunk/jython:1-5562 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-30 02:30:48
|
Revision: 5663 http://jython.svn.sourceforge.net/jython/?rev=5663&view=rev Author: cgroves Date: 2008-11-30 02:30:42 +0000 (Sun, 30 Nov 2008) Log Message: ----------- Hook bean events up in PyJavaType. All of test_java_integration passes again. Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/PyBeanEvent.java branches/newstyle-java-types/src/org/python/core/PyBeanEventProperty.java branches/newstyle-java-types/src/org/python/core/PyCompoundCallable.java branches/newstyle-java-types/src/org/python/core/PyException.java branches/newstyle-java-types/src/org/python/core/PyJavaType.java Modified: branches/newstyle-java-types/src/org/python/core/PyBeanEvent.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyBeanEvent.java 2008-11-30 00:40:22 UTC (rev 5662) +++ branches/newstyle-java-types/src/org/python/core/PyBeanEvent.java 2008-11-30 02:30:42 UTC (rev 5663) @@ -1,13 +1,17 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; + import java.lang.reflect.Method; -public class PyBeanEvent extends PyObject { +public class PyBeanEvent<T> extends PyObject { + public Method addMethod; - public Class eventClass; + + public Class<T> eventClass; + public String __name__; - public PyBeanEvent(String name, Class eventClass, Method addMethod) { + public PyBeanEvent(String name, Class<T> eventClass, Method addMethod) { __name__ = name.intern(); this.addMethod = addMethod; this.eventClass = eventClass; @@ -17,16 +21,15 @@ throw Py.TypeError("write only attribute"); } - boolean _jdontdel() { + boolean jdontdel() { throw Py.TypeError("can't delete this attribute"); } public boolean _doset(PyObject self, PyObject value) { Object jself = Py.tojava(self, addMethod.getDeclaringClass()); - Object jvalue = Py.tojava(value, eventClass); - + T jvalue = Py.tojava(value, eventClass); try { - addMethod.invoke(jself, new Object[] {jvalue}); + addMethod.invoke(jself, jvalue); } catch (Exception e) { throw Py.JavaError(e); } Modified: branches/newstyle-java-types/src/org/python/core/PyBeanEventProperty.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyBeanEventProperty.java 2008-11-30 00:40:22 UTC (rev 5662) +++ branches/newstyle-java-types/src/org/python/core/PyBeanEventProperty.java 2008-11-30 02:30:42 UTC (rev 5663) @@ -9,16 +9,29 @@ import org.python.util.Generic; -public class PyBeanEventProperty extends PyReflectedField -{ +public class PyBeanEventProperty extends PyReflectedField { + + private static Map<String, Class<?>> adapterClasses = Generic.map(); + + private static Map<Object, Map<String, WeakReference<Object>>> adapters = + new WeakHashMap<Object, Map<String, WeakReference<Object>>>(); + public Method addMethod; + public String eventName; - public Class eventClass; + + public Class<?> eventClass; + public String __name__; - public PyBeanEventProperty(String eventName, Class eventClass, - Method addMethod, Method eventMethod) - { + private Field adapterField; + + private Class<?> adapterClass; + + public PyBeanEventProperty(String eventName, + Class<?> eventClass, + Method addMethod, + Method eventMethod) { __name__ = eventMethod.getName().intern(); this.addMethod = addMethod; this.eventName = eventName; @@ -26,47 +39,50 @@ } public PyObject _doget(PyObject self) { - if (self == null) + if (self == null) { return this; - + } initAdapter(); - Object jself = Py.tojava(self, addMethod.getDeclaringClass()); - Object field; try { field = adapterField.get(getAdapter(jself)); } catch (Exception exc) { throw Py.JavaError(exc); } - PyCompoundCallable func; if (field == null) { func = new PyCompoundCallable(); setFunction(jself, func); return func; } - if (field instanceof PyCompoundCallable) + if (field instanceof PyCompoundCallable) { return (PyCompoundCallable)field; - + } func = new PyCompoundCallable(); setFunction(jself, func); func.append((PyObject)field); return func; } - private synchronized static Class<?> getAdapterClass(Class<?> c) { - Class<?> pc = Py.findClass("org.python.proxies." + c.getName() + "$Adapter"); - if (pc == null) { - pc = MakeProxies.makeAdapter(c); + public boolean _doset(PyObject self, PyObject value) { + Object jself = Py.tojava(self, addMethod.getDeclaringClass()); + if (!(value instanceof PyCompoundCallable)) { + PyCompoundCallable func = new PyCompoundCallable(); + setFunction(jself, func); + func.append(value); + } else { + setFunction(jself, value); } - return pc; + return true; } - protected Map<Object, Map<String, WeakReference<Object>>> adapters = - new WeakHashMap<Object, Map<String, WeakReference<Object>>>(); + public String toString() { + return "<beanEventProperty " + __name__ + " for event " + eventClass.toString() + " " + + Py.idstr(this) + ">"; + } - protected Object getAdapter(Object o, String evc) { + private Object getAdapter(Object o, String evc) { Map<String, WeakReference<Object>> ads = adapters.get(o); if (ads == null) { return null; @@ -78,9 +94,9 @@ return adw.get(); } - protected void putAdapter(Object o, String evc, Object ad) { + private void putAdapter(Object o, String evc, Object ad) { Map<String, WeakReference<Object>> ads = adapters.get(o); - if(ads == null) { + if (ads == null) { ads = Generic.map(); adapters.put(o, ads); } @@ -90,11 +106,12 @@ private synchronized Object getAdapter(Object self) { String eventClassName = eventClass.getName(); Object adapter = getAdapter(self, eventClassName); - if (adapter != null) + if (adapter != null) { return adapter; + } try { adapter = adapterClass.newInstance(); - addMethod.invoke(self, new Object[] {adapter}); + addMethod.invoke(self, adapter); } catch (Exception e) { throw Py.JavaError(e); } @@ -102,14 +119,9 @@ return adapter; } - private Field adapterField; - private Class adapterClass; - private void initAdapter() { if (adapterClass == null) { adapterClass = getAdapterClass(eventClass); - } - if (adapterField == null) { try { adapterField = adapterClass.getField(__name__); } catch (NoSuchFieldException exc) { @@ -127,20 +139,16 @@ } } - public boolean _doset(PyObject self, PyObject value) { - Object jself = Py.tojava(self, addMethod.getDeclaringClass()); - if (!(value instanceof PyCompoundCallable)) { - PyCompoundCallable func = new PyCompoundCallable(); - setFunction(jself, func); - func.append(value); - } else { - setFunction(jself, value); + private synchronized static Class<?> getAdapterClass(Class<?> c) { + String name = "org.python.proxies." + c.getName() + "$Adapter"; + Class<?> pc = Py.findClass(name); + if (pc == null) { + pc = adapterClasses.get(name); + if (pc == null) { + pc = MakeProxies.makeAdapter(c); + adapterClasses.put(name, pc); + } } - return true; + return pc; } - - public String toString() { - return "<beanEventProperty "+__name__+" for event "+ - eventClass.toString()+" "+Py.idstr(this)+">"; - } } Modified: branches/newstyle-java-types/src/org/python/core/PyCompoundCallable.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyCompoundCallable.java 2008-11-30 00:40:22 UTC (rev 5662) +++ branches/newstyle-java-types/src/org/python/core/PyCompoundCallable.java 2008-11-30 02:30:42 UTC (rev 5663) @@ -1,36 +1,34 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.util.Vector; +import java.util.List; + +import org.python.util.Generic; + public class PyCompoundCallable extends PyObject { - private Vector callables; - private PySystemState systemState; - public PyCompoundCallable () { - callables = new Vector(); - systemState = Py.getSystemState(); - } + private List<PyObject> callables = Generic.list(); + private PySystemState systemState = Py.getSystemState(); + public void append(PyObject callable) { - callables.addElement(callable); + callables.add(callable); } public void clear() { - callables.removeAllElements(); + callables.clear(); } public PyObject __call__(PyObject[] args, String[] keywords) { // Set the system state to handle callbacks from java threads Py.setSystemState(systemState); - int n = callables.size(); - //System.out.println("callable: "+n); - for (int i=0; i<n; i++) { - ((PyObject)callables.elementAt(i)).__call__(args, keywords); + for (PyObject callable : callables) { + callable.__call__(args, keywords); } return Py.None; } public String toString() { - return "<CompoundCallable with "+callables.size()+" callables>"; + return "<CompoundCallable with " + callables.size() + " callables>"; } } Modified: branches/newstyle-java-types/src/org/python/core/PyException.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyException.java 2008-11-30 00:40:22 UTC (rev 5662) +++ branches/newstyle-java-types/src/org/python/core/PyException.java 2008-11-30 02:30:42 UTC (rev 5663) @@ -65,12 +65,9 @@ public void printStackTrace() { Py.printException(this); } - + public Throwable fillInStackTrace() { - if (Options.includeJavaStackInExceptions) - return super.fillInStackTrace(); - else - return this; + return Options.includeJavaStackInExceptions ? super.fillInStackTrace() : this; } public synchronized void printStackTrace(PrintStream s) { Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-30 00:40:22 UTC (rev 5662) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-30 02:30:42 UTC (rev 5663) @@ -7,6 +7,7 @@ import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Enumeration; +import java.util.EventListener; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -18,138 +19,8 @@ private final static Class<?>[] OO = {PyObject.class, PyObject.class}; + private static Map<Class<?>, PyBuiltinMethod[]> collectionProxies; - class EnumerationIter extends PyIterator { - - private Enumeration<Object> proxy; - - public EnumerationIter(Enumeration<Object> proxy) { - this.proxy = proxy; - } - - public PyObject __iternext__() { - return proxy.hasMoreElements() ? Py.java2py(proxy.nextElement()) : null; - } - } - - private static class IteratorIter extends PyIterator { - - private Iterator<Object> proxy; - - public IteratorIter(Iterator<Object> proxy) { - this.proxy = proxy; - } - - public PyObject __iternext__() { - return proxy.hasNext() ? Py.java2py(proxy.next()) : null; - } - } - - static Map<Class<?>, PyBuiltinMethod[]> _collectionProxies; - - protected static class ListMethod extends PyBuiltinMethodNarrow { - protected ListMethod(String name, int minArgs, int maxArgs) { - super(name, minArgs, maxArgs); - } - - protected List<Object> asList(){ - return (List<Object>)self.getJavaProxy(); - } - } - protected static class MapMethod extends PyBuiltinMethodNarrow { - protected MapMethod(String name, int minArgs, int maxArgs) { - super(name, minArgs, maxArgs); - } - - protected Map<Object, Object> asMap(){ - return (Map<Object, Object>)self.getJavaProxy(); - } - } - - public static Map<Class<?>, PyBuiltinMethod[]> getCollectionProxies() { - if (_collectionProxies == null) { - _collectionProxies = Generic.map(); - - PyBuiltinMethodNarrow lenProxy = new PyBuiltinMethodNarrow("__len__", 0, 0) { - @Override - public PyObject __call__() { - return Py.newInteger(((Collection<?>)self.getJavaProxy()).size()); - } - }; - - PyBuiltinMethodNarrow mapGetProxy = new MapMethod("__getitem__", 1, 1) { - @Override - public PyObject __call__(PyObject key) { - return Py.java2py(asMap().get(Py.tojava(key, Object.class))); - } - }; - - PyBuiltinMethodNarrow mapPutProxy = new MapMethod("__setitem__", 2, 2) { - @Override - public PyObject __call__(PyObject key, PyObject value) { - return Py.java2py(asMap().put(Py.tojava(key, Object.class), - Py.tojava(value, Object.class))); - } - }; - - PyBuiltinMethodNarrow mapRemoveProxy = new MapMethod("__delitem__", 1, 1) { - @Override - public PyObject __call__(PyObject key, PyObject value) { - return Py.java2py(asMap().remove(Py.tojava(key, Object.class))); - } - }; - - PyBuiltinMethodNarrow listGetProxy = new ListMethod("__getitem__", 1, 1) { - @Override - public PyObject __call__(PyObject key) { - if (key instanceof PyInteger) { - return Py.java2py(asList().get(((PyInteger)key).getValue())); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } - }; - - PyBuiltinMethodNarrow listSetProxy = new ListMethod("__setitem__", 2, 2) { - @Override - public PyObject __call__(PyObject key, PyObject value) { - if (key instanceof PyInteger) { - asList().set(((PyInteger)key).getValue(), Py.tojava(value, Object.class)); - } else { - throw Py.TypeError("only integer keys accepted"); - } - return Py.None; - } - }; - - PyBuiltinMethodNarrow listRemoveProxy = new ListMethod("__delitem__", 1, 1) { - @Override - public PyObject __call__(PyObject key, PyObject value) { - if (key instanceof PyInteger) { - return Py.java2py(asList().remove(((PyInteger)key).getValue())); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } - }; - - PyBuiltinMethodNarrow iterableProxy = new PyBuiltinMethodNarrow("__iter__", 0, 0) { - public PyObject __call__() { - return new IteratorIter(((Iterable)self.getJavaProxy()).iterator()); - } - }; - _collectionProxies.put(Iterable.class, new PyBuiltinMethod[] {iterableProxy}); - _collectionProxies.put(Collection.class, new PyBuiltinMethod[] {lenProxy}); - _collectionProxies.put(Map.class, new PyBuiltinMethod[] {mapGetProxy, - mapPutProxy, - mapRemoveProxy}); - _collectionProxies.put(List.class, new PyBuiltinMethod[] {listGetProxy, - listSetProxy, - listRemoveProxy}); - } - return _collectionProxies; - } - public static PyObject wrapJavaObject(Object o) { PyObject obj = new PyObjectDerived(PyType.fromClass(o.getClass())); obj.javaProxy = o; @@ -172,6 +43,7 @@ // Add methods and determine bean properties declared on this class Map<String, PyBeanProperty> props = Generic.map(); + Map<String, PyBeanEvent> events = Generic.map(); for (Method meth : underlying_class.getMethods()) { if (!declaredOnMember(base, meth) || ignore(meth)) { continue; @@ -184,34 +56,54 @@ } else { reflfunc.addMethod(meth); } - if (!Modifier.isStatic(meth.getModifiers())) { - // check for xxxX.* - int n = meth.getParameterTypes().length; - String name = null; - boolean get = true; - if (methname.startsWith("get") && methname.length() > 3 && n == 0) { - name = methname.substring(3); - } else if (methname.startsWith("is") && methname.length() > 2 && n == 0 - && meth.getReturnType() == Boolean.TYPE) { - name = methname.substring(2); - } else if (methname.startsWith("set") && methname.length() > 3 && n == 1) { - name = methname.substring(3); - get = false; + + // Now check if this is a bean method, for which it must be an instance method + if (Modifier.isStatic(meth.getModifiers())) { + continue; + } + + // First check if this is a bean event addition method + int n = meth.getParameterTypes().length; + if ((methname.startsWith("add") || methname.startsWith("set")) + && methname.endsWith("Listener") && n == 1 && + meth.getReturnType() == Void.TYPE && + EventListener.class.isAssignableFrom(meth.getParameterTypes()[0])) { + Class<?> eventClass = meth.getParameterTypes()[0]; + String ename = eventClass.getName(); + int idot = ename.lastIndexOf('.'); + if (idot != -1) { + ename = ename.substring(idot + 1); } - if (name != null) { - name = normalize(StringUtil.decapitalize(name)); - PyBeanProperty prop = props.get(name); - if (prop == null) { - prop = new PyBeanProperty(name, null, null, null); - props.put(name, prop); - } - if (get) { - prop.getMethod = meth; - prop.myType = meth.getReturnType(); - } else { - prop.setMethod = meth; - } + ename = normalize(StringUtil.decapitalize(ename)); + events.put(ename, new PyBeanEvent(name, eventClass, meth)); + continue; + } + + // Now check if it's a bean property accessor + String name = null; + boolean get = true; + if (methname.startsWith("get") && methname.length() > 3 && n == 0) { + name = methname.substring(3); + } else if (methname.startsWith("is") && methname.length() > 2 && n == 0 + && meth.getReturnType() == Boolean.TYPE) { + name = methname.substring(2); + } else if (methname.startsWith("set") && methname.length() > 3 && n == 1) { + name = methname.substring(3); + get = false; + } + if (name != null) { + name = normalize(StringUtil.decapitalize(name)); + PyBeanProperty prop = props.get(name); + if (prop == null) { + prop = new PyBeanProperty(name, null, null, null); + props.put(name, prop); } + if (get) { + prop.getMethod = meth; + prop.myType = meth.getReturnType(); + } else { + prop.setMethod = meth; + } } } @@ -251,6 +143,23 @@ } } + for (PyBeanEvent ev : events.values()) { + if (dict.__finditem__(ev.__name__) == null) { + dict.__setitem__(ev.__name__, ev); + } + + for (Method meth : ev.eventClass.getMethods()) { + String name = meth.getName().intern(); + if (dict.__finditem__(name) != null) { + continue; + } + dict.__setitem__(name, new PyBeanEventProperty(name, + ev.eventClass, + ev.addMethod, + meth)); + } + } + // Fill in the bean properties picked up while going through the methods for (PyBeanProperty prop : props.values()) { PyObject prev = dict.__finditem__(prop.__name__); @@ -362,4 +271,134 @@ } return false; } + + private class EnumerationIter extends PyIterator { + + private Enumeration<Object> proxy; + + public EnumerationIter(Enumeration<Object> proxy) { + this.proxy = proxy; + } + + public PyObject __iternext__() { + return proxy.hasMoreElements() ? Py.java2py(proxy.nextElement()) : null; + } + } + + private static class IteratorIter extends PyIterator { + + private Iterator<Object> proxy; + + public IteratorIter(Iterator<Object> proxy) { + this.proxy = proxy; + } + + public PyObject __iternext__() { + return proxy.hasNext() ? Py.java2py(proxy.next()) : null; + } + } + + private static class ListMethod extends PyBuiltinMethodNarrow { + protected ListMethod(String name, int minArgs, int maxArgs) { + super(name, minArgs, maxArgs); + } + + protected List<Object> asList(){ + return (List<Object>)self.getJavaProxy(); + } + } + + private static class MapMethod extends PyBuiltinMethodNarrow { + protected MapMethod(String name, int minArgs, int maxArgs) { + super(name, minArgs, maxArgs); + } + + protected Map<Object, Object> asMap(){ + return (Map<Object, Object>)self.getJavaProxy(); + } + } + + private static Map<Class<?>, PyBuiltinMethod[]> getCollectionProxies() { + if (collectionProxies == null) { + collectionProxies = Generic.map(); + + PyBuiltinMethodNarrow lenProxy = new PyBuiltinMethodNarrow("__len__", 0, 0) { + @Override + public PyObject __call__() { + return Py.newInteger(((Collection<?>)self.getJavaProxy()).size()); + } + }; + + PyBuiltinMethodNarrow mapGetProxy = new MapMethod("__getitem__", 1, 1) { + @Override + public PyObject __call__(PyObject key) { + return Py.java2py(asMap().get(Py.tojava(key, Object.class))); + } + }; + + PyBuiltinMethodNarrow mapPutProxy = new MapMethod("__setitem__", 2, 2) { + @Override + public PyObject __call__(PyObject key, PyObject value) { + return Py.java2py(asMap().put(Py.tojava(key, Object.class), + Py.tojava(value, Object.class))); + } + }; + + PyBuiltinMethodNarrow mapRemoveProxy = new MapMethod("__delitem__", 1, 1) { + @Override + public PyObject __call__(PyObject key, PyObject value) { + return Py.java2py(asMap().remove(Py.tojava(key, Object.class))); + } + }; + + PyBuiltinMethodNarrow listGetProxy = new ListMethod("__getitem__", 1, 1) { + @Override + public PyObject __call__(PyObject key) { + if (key instanceof PyInteger) { + return Py.java2py(asList().get(((PyInteger)key).getValue())); + } else { + throw Py.TypeError("only integer keys accepted"); + } + } + }; + + PyBuiltinMethodNarrow listSetProxy = new ListMethod("__setitem__", 2, 2) { + @Override + public PyObject __call__(PyObject key, PyObject value) { + if (key instanceof PyInteger) { + asList().set(((PyInteger)key).getValue(), Py.tojava(value, Object.class)); + } else { + throw Py.TypeError("only integer keys accepted"); + } + return Py.None; + } + }; + + PyBuiltinMethodNarrow listRemoveProxy = new ListMethod("__delitem__", 1, 1) { + @Override + public PyObject __call__(PyObject key, PyObject value) { + if (key instanceof PyInteger) { + return Py.java2py(asList().remove(((PyInteger)key).getValue())); + } else { + throw Py.TypeError("only integer keys accepted"); + } + } + }; + + PyBuiltinMethodNarrow iterableProxy = new PyBuiltinMethodNarrow("__iter__", 0, 0) { + public PyObject __call__() { + return new IteratorIter(((Iterable)self.getJavaProxy()).iterator()); + } + }; + collectionProxies.put(Iterable.class, new PyBuiltinMethod[] {iterableProxy}); + collectionProxies.put(Collection.class, new PyBuiltinMethod[] {lenProxy}); + collectionProxies.put(Map.class, new PyBuiltinMethod[] {mapGetProxy, + mapPutProxy, + mapRemoveProxy}); + collectionProxies.put(List.class, new PyBuiltinMethod[] {listGetProxy, + listSetProxy, + listRemoveProxy}); + } + return collectionProxies; + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-30 00:40:26
|
Revision: 5662 http://jython.svn.sourceforge.net/jython/?rev=5662&view=rev Author: cgroves Date: 2008-11-30 00:40:22 +0000 (Sun, 30 Nov 2008) Log Message: ----------- Make java.lang.Object and Java interfaces descend from the Python object type. This changed the class initialization order, so put static constants in PyJavaType in a static method so they're actually initialized at time of use. Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/PyBeanProperty.java branches/newstyle-java-types/src/org/python/core/PyJavaType.java branches/newstyle-java-types/src/org/python/core/PyType.java Modified: branches/newstyle-java-types/src/org/python/core/PyBeanProperty.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyBeanProperty.java 2008-11-29 07:43:57 UTC (rev 5661) +++ branches/newstyle-java-types/src/org/python/core/PyBeanProperty.java 2008-11-30 00:40:22 UTC (rev 5662) @@ -53,10 +53,9 @@ // Special handling of tuples - try to call a class constructor if (value instanceof PyTuple) { try { - PyTuple vtup = (PyTuple)value; - value = Py.java2py(myType).__call__(vtup.getArray()); // xxx PyObject subclasses + value = Py.java2py(myType).__call__(((PyTuple)value).getArray()); } catch (Throwable t) { - // If something goes wrong ignore it? + throw Py.JavaError(t); } } Object jvalue = Py.tojava(value, myType); Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-29 07:43:57 UTC (rev 5661) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-30 00:40:22 UTC (rev 5662) @@ -18,6 +18,138 @@ private final static Class<?>[] OO = {PyObject.class, PyObject.class}; + + class EnumerationIter extends PyIterator { + + private Enumeration<Object> proxy; + + public EnumerationIter(Enumeration<Object> proxy) { + this.proxy = proxy; + } + + public PyObject __iternext__() { + return proxy.hasMoreElements() ? Py.java2py(proxy.nextElement()) : null; + } + } + + private static class IteratorIter extends PyIterator { + + private Iterator<Object> proxy; + + public IteratorIter(Iterator<Object> proxy) { + this.proxy = proxy; + } + + public PyObject __iternext__() { + return proxy.hasNext() ? Py.java2py(proxy.next()) : null; + } + } + + static Map<Class<?>, PyBuiltinMethod[]> _collectionProxies; + + protected static class ListMethod extends PyBuiltinMethodNarrow { + protected ListMethod(String name, int minArgs, int maxArgs) { + super(name, minArgs, maxArgs); + } + + protected List<Object> asList(){ + return (List<Object>)self.getJavaProxy(); + } + } + protected static class MapMethod extends PyBuiltinMethodNarrow { + protected MapMethod(String name, int minArgs, int maxArgs) { + super(name, minArgs, maxArgs); + } + + protected Map<Object, Object> asMap(){ + return (Map<Object, Object>)self.getJavaProxy(); + } + } + + public static Map<Class<?>, PyBuiltinMethod[]> getCollectionProxies() { + if (_collectionProxies == null) { + _collectionProxies = Generic.map(); + + PyBuiltinMethodNarrow lenProxy = new PyBuiltinMethodNarrow("__len__", 0, 0) { + @Override + public PyObject __call__() { + return Py.newInteger(((Collection<?>)self.getJavaProxy()).size()); + } + }; + + PyBuiltinMethodNarrow mapGetProxy = new MapMethod("__getitem__", 1, 1) { + @Override + public PyObject __call__(PyObject key) { + return Py.java2py(asMap().get(Py.tojava(key, Object.class))); + } + }; + + PyBuiltinMethodNarrow mapPutProxy = new MapMethod("__setitem__", 2, 2) { + @Override + public PyObject __call__(PyObject key, PyObject value) { + return Py.java2py(asMap().put(Py.tojava(key, Object.class), + Py.tojava(value, Object.class))); + } + }; + + PyBuiltinMethodNarrow mapRemoveProxy = new MapMethod("__delitem__", 1, 1) { + @Override + public PyObject __call__(PyObject key, PyObject value) { + return Py.java2py(asMap().remove(Py.tojava(key, Object.class))); + } + }; + + PyBuiltinMethodNarrow listGetProxy = new ListMethod("__getitem__", 1, 1) { + @Override + public PyObject __call__(PyObject key) { + if (key instanceof PyInteger) { + return Py.java2py(asList().get(((PyInteger)key).getValue())); + } else { + throw Py.TypeError("only integer keys accepted"); + } + } + }; + + PyBuiltinMethodNarrow listSetProxy = new ListMethod("__setitem__", 2, 2) { + @Override + public PyObject __call__(PyObject key, PyObject value) { + if (key instanceof PyInteger) { + asList().set(((PyInteger)key).getValue(), Py.tojava(value, Object.class)); + } else { + throw Py.TypeError("only integer keys accepted"); + } + return Py.None; + } + }; + + PyBuiltinMethodNarrow listRemoveProxy = new ListMethod("__delitem__", 1, 1) { + @Override + public PyObject __call__(PyObject key, PyObject value) { + if (key instanceof PyInteger) { + return Py.java2py(asList().remove(((PyInteger)key).getValue())); + } else { + throw Py.TypeError("only integer keys accepted"); + } + } + }; + + PyBuiltinMethodNarrow iterableProxy = new PyBuiltinMethodNarrow("__iter__", 0, 0) { + public PyObject __call__() { + return new IteratorIter(((Iterable)self.getJavaProxy()).iterator()); + } + }; + _collectionProxies.put(Iterable.class, new PyBuiltinMethod[] {iterableProxy}); + _collectionProxies.put(Collection.class, new PyBuiltinMethod[] {lenProxy}); + _collectionProxies.put(Map.class, new PyBuiltinMethod[] {mapGetProxy, + mapPutProxy, + mapRemoveProxy}); + _collectionProxies.put(List.class, new PyBuiltinMethod[] {listGetProxy, + listSetProxy, + listRemoveProxy}); + } + return _collectionProxies; + } + public static PyObject wrapJavaObject(Object o) { PyObject obj = new PyObjectDerived(PyType.fromClass(o.getClass())); obj.javaProxy = o; @@ -162,14 +294,13 @@ for (Class<?> inner : underlying_class.getClasses()) { dict.__setitem__(inner.getSimpleName(), PyType.fromClass(inner)); } - for (Map.Entry<Class<?>, PyBuiltinMethod[]> entry : _collectionProxies.entrySet()) { + for (Map.Entry<Class<?>, PyBuiltinMethod[]> entry : getCollectionProxies().entrySet()) { if (entry.getKey().isAssignableFrom(underlying_class)) { for (PyBuiltinMethod meth : entry.getValue()) { dict.__setitem__(meth.info.getName(), new PyMethodDescr(this, meth)); } } } - dict.__setitem__("__eq__", new PyMethodDescr(this, EQUALS_PROXY)); if (ClassDictInit.class.isAssignableFrom(underlying_class) && underlying_class != ClassDictInit.class) { try { @@ -184,6 +315,16 @@ || getDescrMethod(underlying_class, "_doset", OO) != null; has_delete = getDescrMethod(underlying_class, "__delete__", PyObject.class) != null || getDescrMethod(underlying_class, "_dodel", PyObject.class) != null; + } else { + // Pass __eq__ through to subclasses of Object + PyBuiltinCallable equals = new PyBuiltinMethodNarrow("__eq__", 1, 1) { + @Override + public PyObject __call__(PyObject o) { + Object oAsJava = o.__tojava__(self.getJavaProxy().getClass()); + return self.getJavaProxy().equals(oAsJava) ? Py.True : Py.False; + } + }; + dict.__setitem__("__eq__", new PyMethodDescr(this, equals)); } } @@ -221,130 +362,4 @@ } return false; } - - private static final PyBuiltinMethodNarrow LEN_PROXY = - new PyBuiltinMethodNarrow("__len__", 0, 0) { - @Override - public PyObject __call__() { - return Py.newInteger(((Collection<?>)self.getJavaProxy()).size()); - } - }; - - private static final PyBuiltinMethodNarrow MAP_GET_PROXY = - new PyBuiltinMethodNarrow("__getitem__", 1, 1) { - @Override - public PyObject __call__(PyObject key) { - return Py.java2py(((Map<?, ?>)self.getJavaProxy()).get(Py.tojava(key, Object.class))); - } - }; - - private static final PyBuiltinMethodNarrow MAP_PUT_PROXY = - new PyBuiltinMethodNarrow("__setitem__", 2, 2) { - @Override - public PyObject __call__(PyObject key, PyObject value) { - return Py.java2py(((Map<Object, Object>)self.getJavaProxy()).put(Py.tojava(key, Object.class), - Py.tojava(value, - Object.class))); - } - }; - - private static final PyBuiltinMethodNarrow MAP_REMOVE_PROXY = - new PyBuiltinMethodNarrow("__delitem__", 1, 1) { - @Override - public PyObject __call__(PyObject key, PyObject value) { - return Py.java2py(((Map<?, ?>)self.getJavaProxy()).remove(Py.tojava(key, Object.class))); - } - }; - - private static final PyBuiltinMethodNarrow LIST_GET_PROXY = - new PyBuiltinMethodNarrow("__getitem__", 1, 1){ - @Override - public PyObject __call__(PyObject key) { - if (key instanceof PyInteger) { - return Py.java2py(((List<?>)self.getJavaProxy()).get(((PyInteger)key).getValue())); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } - }; - - private static final PyBuiltinMethodNarrow LIST_SET_PROXY = - new PyBuiltinMethodNarrow("__setitem__", 2, 2) { - @Override - public PyObject __call__(PyObject key, PyObject value) { - if (key instanceof PyInteger) { - ((List<Object>)self.getJavaProxy()).set(((PyInteger)key).getValue(), - Py.tojava(value, Object.class)); - } else { - throw Py.TypeError("only integer keys accepted"); - } - return Py.None; - } - }; - - private static final PyBuiltinMethodNarrow LIST_REMOVE_PROXY = - new PyBuiltinMethodNarrow("__delitem__", 1, 1) { - @Override - public PyObject __call__(PyObject key, PyObject value) { - if (key instanceof PyInteger) { - return Py.java2py(((List<Object>)self.getJavaProxy()).remove(((PyInteger)key).getValue())); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } - }; - class EnumerationIter extends PyIterator { - - private Enumeration<Object> proxy; - - public EnumerationIter(Enumeration<Object> proxy) { - this.proxy = proxy; - } - - public PyObject __iternext__() { - return proxy.hasMoreElements() ? Py.java2py(proxy.nextElement()) : null; - } - } - - private static class IteratorIter extends PyIterator { - - private Iterator<Object> proxy; - - public IteratorIter(Iterator<Object> proxy) { - this.proxy = proxy; - } - - public PyObject __iternext__() { - return proxy.hasNext() ? Py.java2py(proxy.next()) : null; - } - } - - - private static final PyBuiltinMethodNarrow ITERABLE_PROXY = - new PyBuiltinMethodNarrow("__iter__", 0, 0) { - public PyObject __call__() { - return new IteratorIter(((Iterable)self.getJavaProxy()).iterator()); - } - }; - - private static final PyBuiltinMethodNarrow EQUALS_PROXY = - new PyBuiltinMethodNarrow("__eq__", 1, 1) { - @Override - public PyObject __call__(PyObject o) { - return self.getJavaProxy().equals(o.__tojava__(self.getJavaProxy().getClass())) ? - Py.True : Py.False; - } - }; - - static Map<Class<?>, PyBuiltinMethod[]> _collectionProxies = Generic.map(); - static { - _collectionProxies.put(Iterable.class, new PyBuiltinMethod[] {ITERABLE_PROXY}); - _collectionProxies.put(Collection.class, new PyBuiltinMethod[] {LEN_PROXY}); - _collectionProxies.put(Map.class, new PyBuiltinMethod[] {MAP_GET_PROXY, - MAP_PUT_PROXY, - MAP_REMOVE_PROXY}); - _collectionProxies.put(List.class, new PyBuiltinMethod[] {LIST_GET_PROXY, - LIST_SET_PROXY, - LIST_REMOVE_PROXY}); - } } Modified: branches/newstyle-java-types/src/org/python/core/PyType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyType.java 2008-11-29 07:43:57 UTC (rev 5661) +++ branches/newstyle-java-types/src/org/python/core/PyType.java 2008-11-30 00:40:22 UTC (rev 5662) @@ -341,11 +341,11 @@ } private static void fillInMRO(PyType type, Class<?> base) { - if (base == Object.class || base == null) { - if (type.underlying_class == PyObject.class) { - type.mro = new PyType[] {type}; - return; - } + if (type.underlying_class == PyObject.class) { + type.mro = new PyType[] {type}; + return; + } + if (base == null) { base = PyObject.class; } PyType baseType = fromClass(base); @@ -824,7 +824,7 @@ return false; } - // we're not completely initilized yet; follow tp_base + // we're not completely initialized yet; follow tp_base PyType type = this; do { if (type == supertype) { @@ -958,6 +958,13 @@ } else { newtype = new PyJavaType(); } + + // If filling in the type above filled the type under creation, use that one + PyType type = class_to_type.get(c); + if (type != null) { + return type; + } + class_to_type.put(c, newtype); if (base == null) { base = c.getSuperclass(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-29 07:44:06
|
Revision: 5661 http://jython.svn.sourceforge.net/jython/?rev=5661&view=rev Author: pjenvey Date: 2008-11-29 07:43:57 +0000 (Sat, 29 Nov 2008) Log Message: ----------- constantine-0.4 release Modified Paths: -------------- trunk/jython/build.xml Added Paths: ----------- trunk/jython/extlibs/constantine-0.4.jar Removed Paths: ------------- trunk/jython/extlibs/constantine.jar Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2008-11-29 04:59:20 UTC (rev 5660) +++ trunk/jython/build.xml 2008-11-29 07:43:57 UTC (rev 5661) @@ -526,7 +526,7 @@ <zipfileset src="extlibs/jna-posix.jar"/> <!-- <rule pattern="com.sun.jna.**" result="org.python.jna.@1"/> --> <rule pattern="org.jruby.ext.posix.**" result="org.python.posix.@1"/> - <zipfileset src="extlibs/constantine.jar"/> + <zipfileset src="extlibs/constantine-0.4.jar"/> <rule pattern="com.kenai.constantine.**" result="org.python.constantine.@1"/> </jarjar> <unjar src="${output.dir}/jarjar.jar" dest="${jarjar.dir}"> Added: trunk/jython/extlibs/constantine-0.4.jar =================================================================== (Binary files differ) Property changes on: trunk/jython/extlibs/constantine-0.4.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Deleted: trunk/jython/extlibs/constantine.jar =================================================================== (Binary files differ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-11-29 04:59:25
|
Revision: 5660 http://jython.svn.sourceforge.net/jython/?rev=5660&view=rev Author: fwierzbicki Date: 2008-11-29 04:59:20 +0000 (Sat, 29 Nov 2008) Log Message: ----------- Movement towards a PyObject-centric ast. Modified Paths: -------------- branches/astwrite/CoreExposed.includes branches/astwrite/ast/asdl_antlr.py branches/astwrite/src/org/python/antlr/AST.java branches/astwrite/src/org/python/antlr/GrammarActions.java branches/astwrite/src/org/python/antlr/ParseException.java branches/astwrite/src/org/python/antlr/PythonErrorNode.java branches/astwrite/src/org/python/antlr/PythonTree.java branches/astwrite/src/org/python/antlr/PythonTreeAdaptor.java branches/astwrite/src/org/python/antlr/ast/Assert.java branches/astwrite/src/org/python/antlr/ast/Assign.java branches/astwrite/src/org/python/antlr/ast/Attribute.java branches/astwrite/src/org/python/antlr/ast/AugAssign.java branches/astwrite/src/org/python/antlr/ast/BinOp.java branches/astwrite/src/org/python/antlr/ast/BoolOp.java branches/astwrite/src/org/python/antlr/ast/Break.java branches/astwrite/src/org/python/antlr/ast/Call.java branches/astwrite/src/org/python/antlr/ast/ClassDef.java branches/astwrite/src/org/python/antlr/ast/Compare.java branches/astwrite/src/org/python/antlr/ast/Continue.java branches/astwrite/src/org/python/antlr/ast/Delete.java branches/astwrite/src/org/python/antlr/ast/Dict.java branches/astwrite/src/org/python/antlr/ast/Ellipsis.java branches/astwrite/src/org/python/antlr/ast/ExceptHandler.java branches/astwrite/src/org/python/antlr/ast/Exec.java branches/astwrite/src/org/python/antlr/ast/Expr.java branches/astwrite/src/org/python/antlr/ast/Expression.java branches/astwrite/src/org/python/antlr/ast/ExtSlice.java branches/astwrite/src/org/python/antlr/ast/For.java branches/astwrite/src/org/python/antlr/ast/FunctionDef.java branches/astwrite/src/org/python/antlr/ast/GeneratorExp.java branches/astwrite/src/org/python/antlr/ast/Global.java branches/astwrite/src/org/python/antlr/ast/If.java branches/astwrite/src/org/python/antlr/ast/IfExp.java branches/astwrite/src/org/python/antlr/ast/Import.java branches/astwrite/src/org/python/antlr/ast/ImportFrom.java branches/astwrite/src/org/python/antlr/ast/Index.java branches/astwrite/src/org/python/antlr/ast/Interactive.java branches/astwrite/src/org/python/antlr/ast/Lambda.java branches/astwrite/src/org/python/antlr/ast/List.java branches/astwrite/src/org/python/antlr/ast/ListComp.java branches/astwrite/src/org/python/antlr/ast/Module.java branches/astwrite/src/org/python/antlr/ast/Name.java branches/astwrite/src/org/python/antlr/ast/Num.java branches/astwrite/src/org/python/antlr/ast/Pass.java branches/astwrite/src/org/python/antlr/ast/Print.java branches/astwrite/src/org/python/antlr/ast/Raise.java branches/astwrite/src/org/python/antlr/ast/Repr.java branches/astwrite/src/org/python/antlr/ast/Return.java branches/astwrite/src/org/python/antlr/ast/Slice.java branches/astwrite/src/org/python/antlr/ast/Str.java branches/astwrite/src/org/python/antlr/ast/Subscript.java branches/astwrite/src/org/python/antlr/ast/Suite.java branches/astwrite/src/org/python/antlr/ast/TryExcept.java branches/astwrite/src/org/python/antlr/ast/TryFinally.java branches/astwrite/src/org/python/antlr/ast/Tuple.java branches/astwrite/src/org/python/antlr/ast/UnaryOp.java branches/astwrite/src/org/python/antlr/ast/VisitorBase.java branches/astwrite/src/org/python/antlr/ast/While.java branches/astwrite/src/org/python/antlr/ast/With.java branches/astwrite/src/org/python/antlr/ast/Yield.java branches/astwrite/src/org/python/antlr/ast/aliasType.java branches/astwrite/src/org/python/antlr/ast/argumentsType.java branches/astwrite/src/org/python/antlr/ast/boolopType.java branches/astwrite/src/org/python/antlr/ast/cmpopType.java branches/astwrite/src/org/python/antlr/ast/comprehensionType.java branches/astwrite/src/org/python/antlr/ast/excepthandlerType.java branches/astwrite/src/org/python/antlr/ast/exprType.java branches/astwrite/src/org/python/antlr/ast/expr_contextType.java branches/astwrite/src/org/python/antlr/ast/keywordType.java branches/astwrite/src/org/python/antlr/ast/modType.java branches/astwrite/src/org/python/antlr/ast/operatorType.java branches/astwrite/src/org/python/antlr/ast/sliceType.java branches/astwrite/src/org/python/antlr/ast/stmtType.java branches/astwrite/src/org/python/antlr/ast/unaryopType.java branches/astwrite/src/org/python/compiler/ScopesCompiler.java branches/astwrite/src/org/python/modules/Setup.java Added Paths: ----------- branches/astwrite/src/org/python/antlr/ast/AstModule.java Removed Paths: ------------- branches/astwrite/Lib/_ast.py Modified: branches/astwrite/CoreExposed.includes =================================================================== --- branches/astwrite/CoreExposed.includes 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/CoreExposed.includes 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,3 +1,5 @@ +org/python/antlr/AST.class +org/python/antlr/ast/AsmModule.class org/python/core/PyArray.class org/python/core/PyBaseString.class org/python/core/PyBaseException.class Deleted: branches/astwrite/Lib/_ast.py =================================================================== --- branches/astwrite/Lib/_ast.py 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/Lib/_ast.py 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,79 +0,0 @@ -from org.python.antlr.ast.boolopType import And,Or -from org.python.antlr.ast.operatorType import Add,Sub,Mult,Div,FloorDiv,Mod,LShift,RShift,BitOr,BitAnd,BitXor,Pow -from org.python.antlr.ast.cmpopType import Eq,Gt,GtE,In,Is,IsNot,Lt,LtE,NotEq,NotIn -from org.python.antlr.ast.unaryopType import Invert,Not,UAdd,USub -from org.python.core.PyTableCode import PyCF_ONLY_AST -from org.python.antlr.ast.expr_contextType import Load, Store, Del, AugLoad, AugStore, Param - -from org.python.antlr import AST - -from org.python.antlr.ast import Assert -from org.python.antlr.ast import Assign -from org.python.antlr.ast import Attribute -from org.python.antlr.ast import AugAssign -from org.python.antlr.ast import BinOp -from org.python.antlr.ast import BoolOp -from org.python.antlr.ast import Break -from org.python.antlr.ast import Call -from org.python.antlr.ast import ClassDef -from org.python.antlr.ast import Compare -from org.python.antlr.ast import Continue -from org.python.antlr.ast import Delete -from org.python.antlr.ast import Dict -from org.python.antlr.ast import Ellipsis -from org.python.antlr.ast import Exec -from org.python.antlr.ast import Expr -from org.python.antlr.ast import Expression -from org.python.antlr.ast import ExtSlice -from org.python.antlr.ast import For -from org.python.antlr.ast import FunctionDef -from org.python.antlr.ast import GeneratorExp -from org.python.antlr.ast import Global -from org.python.antlr.ast import If -from org.python.antlr.ast import IfExp -from org.python.antlr.ast import Import -from org.python.antlr.ast import ImportFrom -from org.python.antlr.ast import Index -from org.python.antlr.ast import Interactive -from org.python.antlr.ast import Lambda -from org.python.antlr.ast import List -from org.python.antlr.ast import ListComp -from org.python.antlr.ast import Module -from org.python.antlr.ast import Name -from org.python.antlr.ast import Num -from org.python.antlr.ast import Pass -from org.python.antlr.ast import Print -from org.python.antlr.ast import Raise -from org.python.antlr.ast import Repr -from org.python.antlr.ast import Return -from org.python.antlr.ast import Slice -from org.python.antlr.ast import Str -from org.python.antlr.ast import Subscript -from org.python.antlr.ast import Suite -from org.python.antlr.ast import TryExcept -from org.python.antlr.ast import TryFinally -from org.python.antlr.ast import Tuple -from org.python.antlr.ast import UnaryOp -#from org.python.antlr.ast import Unicode -from org.python.antlr.ast import While -from org.python.antlr.ast import With -from org.python.antlr.ast import Yield - -import org.python.antlr.ast.aliasType as alias -import org.python.antlr.ast.argumentsType as arguments -import org.python.antlr.ast.boolopType as boolop -import org.python.antlr.ast.cmpopType as cmpop -import org.python.antlr.ast.comprehensionType as comprehension -import org.python.antlr.ast.excepthandlerType as excepthandler -import org.python.antlr.ast.exprType as expr -import org.python.antlr.ast.expr_contextType as expr_context -import org.python.antlr.ast.keywordType as keyword -import org.python.antlr.ast.modType as mod -import org.python.antlr.ast.operatorType as operator -import org.python.antlr.ast.sliceType as slice -import org.python.antlr.ast.stmtType as stmt -import org.python.antlr.ast.unaryopType as unaryop - -#Set to the same value as the CPython version we are targetting. -#note that this number comes from the revision number in CPython's repository. -__version__ = 43614 Modified: branches/astwrite/ast/asdl_antlr.py =================================================================== --- branches/astwrite/ast/asdl_antlr.py 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/ast/asdl_antlr.py 2008-11-29 04:59:20 UTC (rev 5660) @@ -56,15 +56,24 @@ print >> self.file, "// Autogenerated AST node" print >> self.file, 'package org.python.antlr.ast;' if refersToPythonTree: - print >> self.file, 'import java.util.ArrayList;' print >> self.file, 'import org.python.antlr.PythonTree;' print >> self.file, 'import org.python.antlr.adapter.AstAdapters;' print >> self.file, 'import org.python.antlr.adapter.ListWrapper;' print >> self.file, 'import org.antlr.runtime.CommonToken;' print >> self.file, 'import org.antlr.runtime.Token;' + print >> self.file, 'import org.python.core.Py;' + print >> self.file, 'import org.python.core.PyObject;' + print >> self.file, 'import org.python.core.PyType;' + print >> self.file, 'import org.python.expose.ExposedGet;' + print >> self.file, 'import org.python.expose.ExposedMethod;' + print >> self.file, 'import org.python.expose.ExposedNew;' + print >> self.file, 'import org.python.expose.ExposedSet;' + print >> self.file, 'import org.python.expose.ExposedType;' + if useDataOutput: print >> self.file, 'import java.io.DataOutputStream;' print >> self.file, 'import java.io.IOException;' + print >> self.file, 'import java.util.ArrayList;' print >> self.file def close(self): @@ -143,7 +152,7 @@ self.open("%sType" % name, refersToPythonTree=0) self.emit('import org.python.antlr.AST;', depth) self.emit('', 0) - self.emit("public enum %(name)sType implements AST {" % locals(), depth) + self.emit("public enum %(name)sType {" % locals(), depth) self.emit("UNDEFINED,", depth + 1) for i in range(len(sum.types) - 1): type = sum.types[i] @@ -199,6 +208,10 @@ self.emit("}", depth+1) self.emit("", 0) + self.emit("public %(name)sType(PyType subType) {" % locals(), depth+1) + self.emit("}", depth+1) + self.emit("", 0) + self.emit("public %(name)sType(int ttype, Token token) {" % locals(), depth+1) self.emit("super(ttype, token);", depth+2) self.emit("}", depth+1) @@ -223,6 +236,7 @@ self.open("%sType" % name, useDataOutput=1) self.emit("public class %(name)sType extends PythonTree {" % locals(), depth) + self.emit("public static final PyType TYPE = PyType.fromClass(%sType.class);" % name, depth + 1); for f in product.fields: self.visit(f, depth + 1) self.emit("", depth) @@ -245,8 +259,10 @@ s = "implements %s " % ", ".join(ifaces) else: s = "" + self.emit('@ExposedType(name = "_ast.%s", base = PyObject.class)' % cons.name, depth); self.emit("public class %s extends %sType %s{" % (cons.name, name, s), depth) + self.emit("public static final PyType TYPE = PyType.fromClass(%s.class);" % cons.name, depth); for f in cons.fields: self.visit(f, depth + 1) self.emit("", depth) @@ -377,8 +393,18 @@ def javaConstructors(self, type, clsname, ctorname, fields, depth): if len(fields) > 0: - self.emit("public %s() {}" % (ctorname), depth) + self.emit("public %s() {" % (ctorname), depth) + self.emit("this(TYPE);", depth + 1) + self.emit("}", depth) + self.emit("public %s(PyType subType) {" % (ctorname), depth) + self.emit("super(subType);", depth + 1) + self.emit("}", depth) + + self.emit("@ExposedNew", depth) + self.emit("@ExposedMethod", depth) + self.emit("public void Module___init__(PyObject[] args, String[] keywords) {}", depth) + fpargs = ", ".join(["Object %s" % f.name for f in fields]) self.emit("public %s(%s) {" % (ctorname, fpargs), depth) for f in fields: @@ -421,17 +447,23 @@ str(field.name).capitalize()), depth) self.emit("return %s;" % field.name, depth+1) self.emit("}", depth) - self.emit("public Object get%s() {" % (str(field.name).capitalize()), depth) + self.emit('@ExposedGet(name = "%s")' % field.name, depth) + self.emit("public PyObject get%s() {" % (str(field.name).capitalize()), depth) if field.seq: - self.emit("return new ListWrapper(%s, AstAdapters.%sAdapter);" % (field.name, field.type), depth+1) + #FIXME: temporary + #self.emit("return new ListWrapper(%s, AstAdapters.%sAdapter);" % (field.name, field.type), depth+1) + self.emit("return Py.None;", depth+1) else: - self.emit("return %s;" % field.name, depth+1) + #FIXME: temporary + #self.emit("return %s;" % field.name, depth+1) + self.emit("return Py.None;", depth+1) self.emit("}", depth) + self.emit('@ExposedSet(name = "%s")' % field.name, depth) self.emit("public void set%s(Object %s) {" % (str(field.name).capitalize(), field.name), depth) if field.seq: #self.emit("this.%s = new %s(" % (field.name, self.javaType(field)), depth+1) - self.emit("this.%s = AstAdapters.to_%sList(%s);" % (field.name, str(field.type), field.name), depth+1) + self.emit("//FJW this.%s = AstAdapters.to_%sList(%s);" % (field.name, str(field.type), field.name), depth+1) else: self.emit("this.%s = AstAdapters.to_%s(%s);" % (field.name, str(field.type), field.name), depth+1) self.emit("}", depth) Modified: branches/astwrite/src/org/python/antlr/AST.java =================================================================== --- branches/astwrite/src/org/python/antlr/AST.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/AST.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,8 +1,12 @@ package org.python.antlr; -public interface AST { +import org.python.core.PyObject; +import org.python.core.PyType; +import org.python.expose.ExposedType; + +@ExposedType(name = "_ast.AST", base = PyObject.class) +public abstract class AST extends PyObject { + public static final PyType TYPE = PyType.fromClass(AST.class); public static String[] emptyStringArray = new String[0]; - public String[] get_attributes(); - public String[] get_fields(); } Modified: branches/astwrite/src/org/python/antlr/GrammarActions.java =================================================================== --- branches/astwrite/src/org/python/antlr/GrammarActions.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/GrammarActions.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -308,7 +308,7 @@ return value; } - void recurseSetContext(Tree tree, expr_contextType context) { + void recurseSetContext(PythonTree tree, expr_contextType context) { if (tree instanceof Context) { ((Context)tree).setContext(context); } Modified: branches/astwrite/src/org/python/antlr/ParseException.java =================================================================== --- branches/astwrite/src/org/python/antlr/ParseException.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/ParseException.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -38,7 +38,7 @@ public ParseException(String message, PythonTree n) { this(message, n.getLine(), n.getCharPositionInLine()); this.node = n; - this.token = n.token; + this.token = n.getToken(); } public ParseException(String message, RecognitionException r) { Modified: branches/astwrite/src/org/python/antlr/PythonErrorNode.java =================================================================== --- branches/astwrite/src/org/python/antlr/PythonErrorNode.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/PythonErrorNode.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -24,7 +24,7 @@ return errorNode.isNil(); } - public int getType() { + public int getAntlrType() { return errorNode.getType(); } Modified: branches/astwrite/src/org/python/antlr/PythonTree.java =================================================================== --- branches/astwrite/src/org/python/antlr/PythonTree.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/PythonTree.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,35 +1,50 @@ package org.python.antlr; -import org.antlr.runtime.tree.BaseTree; -import org.antlr.runtime.tree.Tree; +import org.python.core.PyObject; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; +import org.antlr.runtime.tree.CommonTree; +import org.python.core.PyType; import org.python.antlr.ast.VisitorIF; -public class PythonTree extends BaseTree implements AST { +import java.util.ArrayList; +import java.util.List; +public class PythonTree extends AST { + public boolean from_future_checked = false; private int charStartIndex = -1; private int charStopIndex = -1; - + private CommonTree node; + private PythonTree parent; + /** A single token is the payload */ - public Token token; + //private Token token; /** What token indexes bracket all tokens associated with this node * and below? */ - protected int startIndex=-1, stopIndex=-1; + //protected int startIndex=-1, stopIndex=-1; /** Who is the parent node of this node; if null, implies node is root */ - public PythonTree parent; + //private PythonTree parent; /** What index is this node in the child list? Range: 0..n-1 */ - public int childIndex = -1; + //private int childIndex = -1; public PythonTree() { + node = new CommonTree(); } + public PythonTree(PyType subType) { + node = new CommonTree(); + } + + public PythonTree(Token t) { + node = new CommonTree(t); + } + public PythonTree(int ttype, Token t) { CommonToken c = new CommonToken(ttype, t.getText()); c.setLine(t.getLine()); @@ -38,59 +53,51 @@ c.setChannel(t.getChannel()); c.setStartIndex(((CommonToken)t).getStartIndex()); c.setStopIndex(((CommonToken)t).getStopIndex()); - token = c; + node = new CommonTree(c); } - public PythonTree(Token t) { - this.token = t; + public PythonTree(PythonTree tree) { + node = new CommonTree(tree.getNode()); + charStartIndex = tree.getCharStartIndex(); + charStopIndex = tree.getCharStopIndex(); } + + public CommonTree getNode() { + return node; + } - public PythonTree(PythonTree node) { - super(node); - token = node.token; - startIndex = node.startIndex; - stopIndex = node.stopIndex; - charStartIndex = node.getCharStartIndex(); - charStopIndex = node.getCharStopIndex(); - } - public Token getToken() { - return token; + return node.getToken(); } - public Tree dupNode() { + public PythonTree dupNode() { return new PythonTree(this); } public boolean isNil() { - return token==null; + return node.isNil(); } - public int getType() { - if (token==null) { - return Token.INVALID_TOKEN_TYPE; - } - return token.getType(); + public int getAntlrType() { + return node.getType(); } public String getText() { - if (token==null) { - return null; - } - return token.getText(); + return node.getText(); } public int getLine() { - if (token==null || token.getLine()==0) { + if (node.getToken()==null || node.getToken().getLine()==0) { if ( getChildCount()>0 ) { return getChild(0).getLine(); } return 1; } - return token.getLine(); + return node.getToken().getLine(); } public int getCharPositionInLine() { + Token token = node.getToken(); if (token==null || token.getCharPositionInLine()==-1) { if (getChildCount()>0) { return getChild(0).getCharPositionInLine(); @@ -107,46 +114,24 @@ } public int getTokenStartIndex() { - if ( startIndex==-1 && token!=null ) { - return token.getTokenIndex(); - } - return startIndex; + return node.getTokenStartIndex(); } public void setTokenStartIndex(int index) { - startIndex = index; + node.setTokenStartIndex(index); } public int getTokenStopIndex() { - if ( stopIndex==-1 && token!=null ) { - return token.getTokenIndex(); - } - return stopIndex; + return node.getTokenStopIndex(); } public void setTokenStopIndex(int index) { - stopIndex = index; + node.setTokenStopIndex(index); } - public int getChildIndex() { - return childIndex; - } - - public Tree getParent() { - return parent; - } - - public void setParent(Tree t) { - this.parent = (PythonTree)t; - } - - public void setChildIndex(int index) { - this.childIndex = index; - } - public int getCharStartIndex() { - if (charStartIndex == -1 && token != null) { - return ((CommonToken)token).getStartIndex(); + if (charStartIndex == -1 && node.getToken() != null) { + return ((CommonToken)node.getToken()).getStartIndex(); } return charStartIndex ; } @@ -166,8 +151,8 @@ */ public int getCharStopIndex() { - if (charStopIndex == -1 && token != null) { - return ((CommonToken)token).getStopIndex() + 1; + if (charStopIndex == -1 && node.getToken() != null) { + return ((CommonToken)node.getToken()).getStopIndex() + 1; } return charStopIndex; } @@ -176,24 +161,36 @@ charStopIndex = index; } + public int getChildIndex() { + return node.getChildIndex(); + } + + public PythonTree getParent() { + return parent; + } + + public void setParent(PythonTree t) { + this.parent = t; + } + + public void setChildIndex(int index) { + node.setChildIndex(index); + } + public String toString() { if (isNil()) { return "None"; } - if ( getType()==Token.INVALID_TOKEN_TYPE ) { + if ( getAntlrType()==Token.INVALID_TOKEN_TYPE ) { return "<errornode>"; } - if ( token==null ) { + if ( node.getToken()==null ) { return null; } - return token.getText() + "(" + this.getLine() + "," + this.getCharPositionInLine() + ")"; + return node.getToken().getText() + "(" + this.getLine() + "," + this.getCharPositionInLine() + ")"; } - public String info() { - return this.getCharStartIndex() + ":" + this.getCharStopIndex(); - } - public String toStringTree() { if (children == null || children.size() == 0) { return this.toString();// + "[" + this.info() + "]"; @@ -205,7 +202,7 @@ buf.append(' '); } for (int i = 0; children != null && i < children.size(); i++) { - BaseTree t = (BaseTree)children.get(i); + PythonTree t = (PythonTree)children.get(i); if (i > 0) { buf.append(' '); } @@ -260,4 +257,205 @@ public String[] get_attributes() { return emptyStringArray; } + + //Copied from org.antlr.runtime.tree.BaseTree + protected List children; + + public PythonTree getChild(int i) { + if ( children==null || i>=children.size() ) { + return null; + } + return (PythonTree)children.get(i); + } + + /** Get the children internal List; note that if you directly mess with + * the list, do so at your own risk. + */ + public List getChildren() { + return children; + } + + public PythonTree getFirstChildWithType(int type) { + for (int i = 0; children!=null && i < children.size(); i++) { + PythonTree t = (PythonTree) children.get(i); + if ( t.getAntlrType()==type ) { + return t; + } + } + return null; + } + + public int getChildCount() { + if ( children==null ) { + return 0; + } + return children.size(); + } + + /** Add t as child of this node. + * + * Warning: if t has no children, but child does + * and child isNil then this routine moves children to t via + * t.children = child.children; i.e., without copying the array. + */ + public void addChild(PythonTree t) { + //System.out.println("add child "+t.toStringTree()+" "+this.toStringTree()); + //System.out.println("existing children: "+children); + if ( t==null ) { + return; // do nothing upon addChild(null) + } + PythonTree childTree = (PythonTree)t; + if ( childTree.isNil() ) { // t is an empty node possibly with children + if ( this.children!=null && this.children == childTree.children ) { + throw new RuntimeException("attempt to add child list to itself"); + } + // just add all of childTree's children to this + if ( childTree.children!=null ) { + if ( this.children!=null ) { // must copy, this has children already + int n = childTree.children.size(); + for (int i = 0; i < n; i++) { + PythonTree c = (PythonTree)childTree.children.get(i); + this.children.add(c); + // handle double-link stuff for each child of nil root + c.setParent(this); + c.setChildIndex(children.size()-1); + } + } + else { + // no children for this but t has children; just set pointer + // call general freshener routine + this.children = childTree.children; + this.freshenParentAndChildIndexes(); + } + } + } + else { // child is not nil (don't care about children) + if ( children==null ) { + children = createChildrenList(); // create children list on demand + } + children.add(t); + childTree.setParent(this); + childTree.setChildIndex(children.size()-1); + } + // System.out.println("now children are: "+children); + } + + /** Add all elements of kids list as children of this node */ + public void addChildren(List kids) { + for (int i = 0; i < kids.size(); i++) { + PythonTree t = (PythonTree) kids.get(i); + addChild(t); + } + } + + public void setChild(int i, PythonTree t) { + if ( t==null ) { + return; + } + if ( t.isNil() ) { + throw new IllegalArgumentException("Can't set single child to a list"); + } + if ( children==null ) { + children = createChildrenList(); + } + children.set(i, t); + t.setParent(this); + t.setChildIndex(i); + } + + public Object deleteChild(int i) { + if ( children==null ) { + return null; + } + PythonTree killed = (PythonTree)children.remove(i); + // walk rest and decrement their child indexes + this.freshenParentAndChildIndexes(i); + return killed; + } + + /** Delete children from start to stop and replace with t even if t is + * a list (nil-root tree). num of children can increase or decrease. + * For huge child lists, inserting children can force walking rest of + * children to set their childindex; could be slow. + */ + public void replaceChildren(int startChildIndex, int stopChildIndex, Object t) { + /* + System.out.println("replaceChildren "+startChildIndex+", "+stopChildIndex+ + " with "+((PythonTree)t).toStringTree()); + System.out.println("in="+toStringTree()); + */ + if ( children==null ) { + throw new IllegalArgumentException("indexes invalid; no children in list"); + } + int replacingHowMany = stopChildIndex - startChildIndex + 1; + int replacingWithHowMany; + PythonTree newTree = (PythonTree)t; + List newChildren = null; + // normalize to a list of children to add: newChildren + if ( newTree.isNil() ) { + newChildren = newTree.children; + } + else { + newChildren = new ArrayList(1); + newChildren.add(newTree); + } + replacingWithHowMany = newChildren.size(); + int numNewChildren = newChildren.size(); + int delta = replacingHowMany - replacingWithHowMany; + // if same number of nodes, do direct replace + if ( delta == 0 ) { + int j = 0; // index into new children + for (int i=startChildIndex; i<=stopChildIndex; i++) { + PythonTree child = (PythonTree)newChildren.get(j); + children.set(i, child); + child.setParent(this); + child.setChildIndex(i); + j++; + } + } + else if ( delta > 0 ) { // fewer new nodes than there were + // set children and then delete extra + for (int j=0; j<numNewChildren; j++) { + children.set(startChildIndex+j, newChildren.get(j)); + } + int indexToDelete = startChildIndex+numNewChildren; + for (int c=indexToDelete; c<=stopChildIndex; c++) { + // delete same index, shifting everybody down each time + PythonTree killed = (PythonTree)children.remove(indexToDelete); + } + freshenParentAndChildIndexes(startChildIndex); + } + else { // more new nodes than were there before + // fill in as many children as we can (replacingHowMany) w/o moving data + for (int j=0; j<replacingHowMany; j++) { + children.set(startChildIndex+j, newChildren.get(j)); + } + int numToInsert = replacingWithHowMany-replacingHowMany; + for (int j=replacingHowMany; j<replacingWithHowMany; j++) { + children.add(startChildIndex+j, newChildren.get(j)); + } + freshenParentAndChildIndexes(startChildIndex); + } + //System.out.println("out="+toStringTree()); + } + + /** Override in a subclass to change the impl of children list */ + protected List createChildrenList() { + return new ArrayList(); + } + + /** Set the parent and child index values for all child of t */ + public void freshenParentAndChildIndexes() { + freshenParentAndChildIndexes(0); + } + + public void freshenParentAndChildIndexes(int offset) { + int n = getChildCount(); + for (int c = offset; c < n; c++) { + PythonTree child = (PythonTree)getChild(c); + child.setChildIndex(c); + child.setParent(this); + } + } + } Modified: branches/astwrite/src/org/python/antlr/PythonTreeAdaptor.java =================================================================== --- branches/astwrite/src/org/python/antlr/PythonTreeAdaptor.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/PythonTreeAdaptor.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -49,6 +49,104 @@ if (t == null) { return null; } - return create(((PythonTree) t).token); + return create(((PythonTree) t).getToken()); } + + public boolean isNil(Object tree) { + return ((PythonTree)tree).isNil(); + } + + public void addChild(Object t, Object child) { + if ( t!=null && child!=null ) { + ((PythonTree)t).addChild((PythonTree)child); + } + } + + public Object becomeRoot(Object newRoot, Object oldRoot) { + //System.out.println("becomeroot new "+newRoot.toString()+" old "+oldRoot); + PythonTree newRootTree = (PythonTree)newRoot; + PythonTree oldRootTree = (PythonTree)oldRoot; + if ( oldRoot==null ) { + return newRoot; + } + // handle ^(nil real-node) + if ( newRootTree.isNil() ) { + int nc = newRootTree.getChildCount(); + if ( nc==1 ) newRootTree = (PythonTree)newRootTree.getChild(0); + else if ( nc >1 ) { + // TODO: make tree run time exceptions hierarchy + throw new RuntimeException("more than one node as root (TODO: make exception hierarchy)"); + } + } + // add oldRoot to newRoot; addChild takes care of case where oldRoot + // is a flat list (i.e., nil-rooted tree). All children of oldRoot + // are added to newRoot. + newRootTree.addChild(oldRootTree); + return newRootTree; + } + + public Object rulePostProcessing(Object root) { + //System.out.println("rulePostProcessing: "+((PythonTree)root).toStringTree()); + PythonTree r = (PythonTree)root; + if ( r!=null && r.isNil() ) { + if ( r.getChildCount()==0 ) { + r = null; + } + else if ( r.getChildCount()==1 ) { + r = (PythonTree)r.getChild(0); + // whoever invokes rule will set parent and child index + r.setParent(null); + r.setChildIndex(-1); + } + } + return r; + } + + public Object create(int tokenType, Token fromToken) { + fromToken = createToken(fromToken); + //((ClassicToken)fromToken).setType(tokenType); + fromToken.setType(tokenType); + PythonTree t = (PythonTree)create(fromToken); + return t; + } + + public Object create(int tokenType, Token fromToken, String text) { + fromToken = createToken(fromToken); + fromToken.setType(tokenType); + fromToken.setText(text); + PythonTree t = (PythonTree)create(fromToken); + return t; + } + + public Object create(int tokenType, String text) { + Token fromToken = createToken(tokenType, text); + PythonTree t = (PythonTree)create(fromToken); + return t; + } + + public int getType(Object t) { + ((PythonTree)t).getType(); + return 0; + } + + public String getText(Object t) { + return ((PythonTree)t).getText(); + } + + public Object getChild(Object t, int i) { + return ((PythonTree)t).getChild(i); + } + + public void setChild(Object t, int i, Object child) { + ((PythonTree)t).setChild(i, (PythonTree)child); + } + + public Object deleteChild(Object t, int i) { + return ((PythonTree)t).deleteChild(i); + } + + public int getChildCount(Object t) { + return ((PythonTree)t).getChildCount(); + } + } Modified: branches/astwrite/src/org/python/antlr/ast/Assert.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Assert.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/ast/Assert.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,22 +1,34 @@ // Autogenerated AST node package org.python.antlr.ast; -import java.util.ArrayList; import org.python.antlr.PythonTree; import org.python.antlr.adapter.AstAdapters; import org.python.antlr.adapter.ListWrapper; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; +import org.python.core.Py; +import org.python.core.PyObject; +import org.python.core.PyType; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedNew; +import org.python.expose.ExposedSet; +import org.python.expose.ExposedType; import java.io.DataOutputStream; import java.io.IOException; +import java.util.ArrayList; +@ExposedType(name = "_ast.Assert", base = PyObject.class) public class Assert extends stmtType { +public static final PyType TYPE = PyType.fromClass(Assert.class); private exprType test; public exprType getInternalTest() { return test; } - public Object getTest() { - return test; + @ExposedGet(name = "test") + public PyObject getTest() { + return Py.None; } + @ExposedSet(name = "test") public void setTest(Object test) { this.test = AstAdapters.to_expr(test); } @@ -25,9 +37,11 @@ public exprType getInternalMsg() { return msg; } - public Object getMsg() { - return msg; + @ExposedGet(name = "msg") + public PyObject getMsg() { + return Py.None; } + @ExposedSet(name = "msg") public void setMsg(Object msg) { this.msg = AstAdapters.to_expr(msg); } @@ -36,7 +50,15 @@ private final static String[] fields = new String[] {"test", "msg"}; public String[] get_fields() { return fields; } - public Assert() {} + public Assert() { + this(TYPE); + } + public Assert(PyType subType) { + super(subType); + } + @ExposedNew + @ExposedMethod + public void Module___init__(PyObject[] args, String[] keywords) {} public Assert(Object test, Object msg) { setTest(test); setMsg(msg); Modified: branches/astwrite/src/org/python/antlr/ast/Assign.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Assign.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/ast/Assign.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,33 +1,47 @@ // Autogenerated AST node package org.python.antlr.ast; -import java.util.ArrayList; import org.python.antlr.PythonTree; import org.python.antlr.adapter.AstAdapters; import org.python.antlr.adapter.ListWrapper; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; +import org.python.core.Py; +import org.python.core.PyObject; +import org.python.core.PyType; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedNew; +import org.python.expose.ExposedSet; +import org.python.expose.ExposedType; import java.io.DataOutputStream; import java.io.IOException; +import java.util.ArrayList; +@ExposedType(name = "_ast.Assign", base = PyObject.class) public class Assign extends stmtType { +public static final PyType TYPE = PyType.fromClass(Assign.class); private java.util.List<exprType> targets; public java.util.List<exprType> getInternalTargets() { return targets; } - public Object getTargets() { - return new ListWrapper(targets, AstAdapters.exprAdapter); + @ExposedGet(name = "targets") + public PyObject getTargets() { + return Py.None; } + @ExposedSet(name = "targets") public void setTargets(Object targets) { - this.targets = AstAdapters.to_exprList(targets); + //FJW this.targets = AstAdapters.to_exprList(targets); } private exprType value; public exprType getInternalValue() { return value; } - public Object getValue() { - return value; + @ExposedGet(name = "value") + public PyObject getValue() { + return Py.None; } + @ExposedSet(name = "value") public void setValue(Object value) { this.value = AstAdapters.to_expr(value); } @@ -36,7 +50,15 @@ private final static String[] fields = new String[] {"targets", "value"}; public String[] get_fields() { return fields; } - public Assign() {} + public Assign() { + this(TYPE); + } + public Assign(PyType subType) { + super(subType); + } + @ExposedNew + @ExposedMethod + public void Module___init__(PyObject[] args, String[] keywords) {} public Assign(Object targets, Object value) { setTargets(targets); setValue(value); Added: branches/astwrite/src/org/python/antlr/ast/AstModule.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/AstModule.java (rev 0) +++ branches/astwrite/src/org/python/antlr/ast/AstModule.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -0,0 +1,86 @@ +package org.python.antlr.ast; + +import org.python.core.ClassDictInit; +import org.python.core.imp; +import org.python.core.Py; +import org.python.core.PyObject; +import org.python.core.PyType; + +import org.python.antlr.AST; +import org.python.core.exceptions; + +public class AstModule implements ClassDictInit { + + private AstModule() {} + + public static void classDictInit(PyObject dict) { + dict.__setitem__("AST", AST.TYPE); + dict.__setitem__("Module", Module.TYPE); + dict.__setitem__("Assert", Assert.TYPE); + dict.__setitem__("Assign", Assign.TYPE); + dict.__setitem__("Attribute", AugAssign.TYPE); + dict.__setitem__("AugAssign", AugAssign.TYPE); + dict.__setitem__("BinOp", BinOp.TYPE); + dict.__setitem__("BoolOp", BoolOp.TYPE); + dict.__setitem__("Break", Break.TYPE); + dict.__setitem__("Call", Call.TYPE); + dict.__setitem__("ClassDef", ClassDef.TYPE); + dict.__setitem__("Compare", Compare.TYPE); + dict.__setitem__("Continue", Continue.TYPE); + dict.__setitem__("Delete", Delete.TYPE); + dict.__setitem__("Dict", Dict.TYPE); + dict.__setitem__("Ellipsis", Ellipsis.TYPE); +// dict.__setitem__("ErrorExpr", ErrorExpr.TYPE); +// dict.__setitem__("ErrorMod", ErrorMod.TYPE); +// dict.__setitem__("ErrorSlice", ErrorSlice.TYPE); +// dict.__setitem__("ErrorStmt", ErrorStmt.TYPE); + dict.__setitem__("ExceptHandler", ExceptHandler.TYPE); + dict.__setitem__("Exec", Exec.TYPE); + dict.__setitem__("Expr", Expr.TYPE); + dict.__setitem__("Expression", Expression.TYPE); + dict.__setitem__("ExtSlice", ExtSlice.TYPE); + dict.__setitem__("For", For.TYPE); + dict.__setitem__("FunctionDef", FunctionDef.TYPE); + dict.__setitem__("GeneratorExp", GeneratorExp.TYPE); + dict.__setitem__("Global", Global.TYPE); + dict.__setitem__("If", If.TYPE); + dict.__setitem__("IfExp", IfExp.TYPE); + dict.__setitem__("Import", Import.TYPE); + dict.__setitem__("ImportFrom", ImportFrom.TYPE); + dict.__setitem__("Index", Index.TYPE); + dict.__setitem__("Interactive", Interactive.TYPE); + dict.__setitem__("Lambda", Lambda.TYPE); + dict.__setitem__("List", List.TYPE); + dict.__setitem__("ListComp", ListComp.TYPE); + dict.__setitem__("Module", Module.TYPE); + dict.__setitem__("Name", Name.TYPE); + dict.__setitem__("Num", Num.TYPE); + dict.__setitem__("Pass", Pass.TYPE); + dict.__setitem__("Print", Print.TYPE); + dict.__setitem__("Raise", Raise.TYPE); + dict.__setitem__("Repr", Repr.TYPE); + dict.__setitem__("Return", Return.TYPE); + dict.__setitem__("Slice", Slice.TYPE); + dict.__setitem__("Str", Str.TYPE); + dict.__setitem__("Subscript", Subscript.TYPE); + dict.__setitem__("Suite", Suite.TYPE); + dict.__setitem__("TryExcept", TryExcept.TYPE); + dict.__setitem__("TryFinally", TryFinally.TYPE); + dict.__setitem__("Tuple", Tuple.TYPE); + dict.__setitem__("UnaryOp", UnaryOp.TYPE); + dict.__setitem__("While", While.TYPE); + dict.__setitem__("With", With.TYPE); + dict.__setitem__("Yield", Yield.TYPE); + dict.__setitem__("alias", aliasType.TYPE); + dict.__setitem__("arguments", argumentsType.TYPE); + dict.__setitem__("comprehension", comprehensionType.TYPE); + dict.__setitem__("excepthandler", excepthandlerType.TYPE); + dict.__setitem__("expr", exprType.TYPE); + dict.__setitem__("keyword", keywordType.TYPE); + dict.__setitem__("mod", modType.TYPE); + dict.__setitem__("slice", sliceType.TYPE); + dict.__setitem__("stmt", stmtType.TYPE); + dict.__setitem__("operator", imp.importName("org.python.antlr.ast.operatorType", false)); + dict.__setitem__("Add", imp.importName("org.python.antlr.ast.operatorType.Add", false)); + } +} Modified: branches/astwrite/src/org/python/antlr/ast/Attribute.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Attribute.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/ast/Attribute.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,22 +1,34 @@ // Autogenerated AST node package org.python.antlr.ast; -import java.util.ArrayList; import org.python.antlr.PythonTree; import org.python.antlr.adapter.AstAdapters; import org.python.antlr.adapter.ListWrapper; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; +import org.python.core.Py; +import org.python.core.PyObject; +import org.python.core.PyType; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedNew; +import org.python.expose.ExposedSet; +import org.python.expose.ExposedType; import java.io.DataOutputStream; import java.io.IOException; +import java.util.ArrayList; +@ExposedType(name = "_ast.Attribute", base = PyObject.class) public class Attribute extends exprType implements Context { +public static final PyType TYPE = PyType.fromClass(Attribute.class); private exprType value; public exprType getInternalValue() { return value; } - public Object getValue() { - return value; + @ExposedGet(name = "value") + public PyObject getValue() { + return Py.None; } + @ExposedSet(name = "value") public void setValue(Object value) { this.value = AstAdapters.to_expr(value); } @@ -25,9 +37,11 @@ public String getInternalAttr() { return attr; } - public Object getAttr() { - return attr; + @ExposedGet(name = "attr") + public PyObject getAttr() { + return Py.None; } + @ExposedSet(name = "attr") public void setAttr(Object attr) { this.attr = AstAdapters.to_identifier(attr); } @@ -36,9 +50,11 @@ public expr_contextType getInternalCtx() { return ctx; } - public Object getCtx() { - return ctx; + @ExposedGet(name = "ctx") + public PyObject getCtx() { + return Py.None; } + @ExposedSet(name = "ctx") public void setCtx(Object ctx) { this.ctx = AstAdapters.to_expr_context(ctx); } @@ -48,7 +64,15 @@ "ctx"}; public String[] get_fields() { return fields; } - public Attribute() {} + public Attribute() { + this(TYPE); + } + public Attribute(PyType subType) { + super(subType); + } + @ExposedNew + @ExposedMethod + public void Module___init__(PyObject[] args, String[] keywords) {} public Attribute(Object value, Object attr, Object ctx) { setValue(value); setAttr(attr); Modified: branches/astwrite/src/org/python/antlr/ast/AugAssign.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/AugAssign.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/ast/AugAssign.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,22 +1,34 @@ // Autogenerated AST node package org.python.antlr.ast; -import java.util.ArrayList; import org.python.antlr.PythonTree; import org.python.antlr.adapter.AstAdapters; import org.python.antlr.adapter.ListWrapper; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; +import org.python.core.Py; +import org.python.core.PyObject; +import org.python.core.PyType; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedNew; +import org.python.expose.ExposedSet; +import org.python.expose.ExposedType; import java.io.DataOutputStream; import java.io.IOException; +import java.util.ArrayList; +@ExposedType(name = "_ast.AugAssign", base = PyObject.class) public class AugAssign extends stmtType { +public static final PyType TYPE = PyType.fromClass(AugAssign.class); private exprType target; public exprType getInternalTarget() { return target; } - public Object getTarget() { - return target; + @ExposedGet(name = "target") + public PyObject getTarget() { + return Py.None; } + @ExposedSet(name = "target") public void setTarget(Object target) { this.target = AstAdapters.to_expr(target); } @@ -25,9 +37,11 @@ public operatorType getInternalOp() { return op; } - public Object getOp() { - return op; + @ExposedGet(name = "op") + public PyObject getOp() { + return Py.None; } + @ExposedSet(name = "op") public void setOp(Object op) { this.op = AstAdapters.to_operator(op); } @@ -36,9 +50,11 @@ public exprType getInternalValue() { return value; } - public Object getValue() { - return value; + @ExposedGet(name = "value") + public PyObject getValue() { + return Py.None; } + @ExposedSet(name = "value") public void setValue(Object value) { this.value = AstAdapters.to_expr(value); } @@ -48,7 +64,15 @@ "value"}; public String[] get_fields() { return fields; } - public AugAssign() {} + public AugAssign() { + this(TYPE); + } + public AugAssign(PyType subType) { + super(subType); + } + @ExposedNew + @ExposedMethod + public void Module___init__(PyObject[] args, String[] keywords) {} public AugAssign(Object target, Object op, Object value) { setTarget(target); setOp(op); Modified: branches/astwrite/src/org/python/antlr/ast/BinOp.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/BinOp.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/ast/BinOp.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,22 +1,34 @@ // Autogenerated AST node package org.python.antlr.ast; -import java.util.ArrayList; import org.python.antlr.PythonTree; import org.python.antlr.adapter.AstAdapters; import org.python.antlr.adapter.ListWrapper; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; +import org.python.core.Py; +import org.python.core.PyObject; +import org.python.core.PyType; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedNew; +import org.python.expose.ExposedSet; +import org.python.expose.ExposedType; import java.io.DataOutputStream; import java.io.IOException; +import java.util.ArrayList; +@ExposedType(name = "_ast.BinOp", base = PyObject.class) public class BinOp extends exprType { +public static final PyType TYPE = PyType.fromClass(BinOp.class); private exprType left; public exprType getInternalLeft() { return left; } - public Object getLeft() { - return left; + @ExposedGet(name = "left") + public PyObject getLeft() { + return Py.None; } + @ExposedSet(name = "left") public void setLeft(Object left) { this.left = AstAdapters.to_expr(left); } @@ -25,9 +37,11 @@ public operatorType getInternalOp() { return op; } - public Object getOp() { - return op; + @ExposedGet(name = "op") + public PyObject getOp() { + return Py.None; } + @ExposedSet(name = "op") public void setOp(Object op) { this.op = AstAdapters.to_operator(op); } @@ -36,9 +50,11 @@ public exprType getInternalRight() { return right; } - public Object getRight() { - return right; + @ExposedGet(name = "right") + public PyObject getRight() { + return Py.None; } + @ExposedSet(name = "right") public void setRight(Object right) { this.right = AstAdapters.to_expr(right); } @@ -47,7 +63,15 @@ private final static String[] fields = new String[] {"left", "op", "right"}; public String[] get_fields() { return fields; } - public BinOp() {} + public BinOp() { + this(TYPE); + } + public BinOp(PyType subType) { + super(subType); + } + @ExposedNew + @ExposedMethod + public void Module___init__(PyObject[] args, String[] keywords) {} public BinOp(Object left, Object op, Object right) { setLeft(left); setOp(op); Modified: branches/astwrite/src/org/python/antlr/ast/BoolOp.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/BoolOp.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/ast/BoolOp.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,22 +1,34 @@ // Autogenerated AST node package org.python.antlr.ast; -import java.util.ArrayList; import org.python.antlr.PythonTree; import org.python.antlr.adapter.AstAdapters; import org.python.antlr.adapter.ListWrapper; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; +import org.python.core.Py; +import org.python.core.PyObject; +import org.python.core.PyType; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedNew; +import org.python.expose.ExposedSet; +import org.python.expose.ExposedType; import java.io.DataOutputStream; import java.io.IOException; +import java.util.ArrayList; +@ExposedType(name = "_ast.BoolOp", base = PyObject.class) public class BoolOp extends exprType { +public static final PyType TYPE = PyType.fromClass(BoolOp.class); private boolopType op; public boolopType getInternalOp() { return op; } - public Object getOp() { - return op; + @ExposedGet(name = "op") + public PyObject getOp() { + return Py.None; } + @ExposedSet(name = "op") public void setOp(Object op) { this.op = AstAdapters.to_boolop(op); } @@ -25,18 +37,28 @@ public java.util.List<exprType> getInternalValues() { return values; } - public Object getValues() { - return new ListWrapper(values, AstAdapters.exprAdapter); + @ExposedGet(name = "values") + public PyObject getValues() { + return Py.None; } + @ExposedSet(name = "values") public void setValues(Object values) { - this.values = AstAdapters.to_exprList(values); + //FJW this.values = AstAdapters.to_exprList(values); } private final static String[] fields = new String[] {"op", "values"}; public String[] get_fields() { return fields; } - public BoolOp() {} + public BoolOp() { + this(TYPE); + } + public BoolOp(PyType subType) { + super(subType); + } + @ExposedNew + @ExposedMethod + public void Module___init__(PyObject[] args, String[] keywords) {} public BoolOp(Object op, Object values) { setOp(op); setValues(values); Modified: branches/astwrite/src/org/python/antlr/ast/Break.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Break.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/ast/Break.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,15 +1,25 @@ // Autogenerated AST node package org.python.antlr.ast; -import java.util.ArrayList; import org.python.antlr.PythonTree; import org.python.antlr.adapter.AstAdapters; import org.python.antlr.adapter.ListWrapper; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; +import org.python.core.Py; +import org.python.core.PyObject; +import org.python.core.PyType; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedNew; +import org.python.expose.ExposedSet; +import org.python.expose.ExposedType; import java.io.DataOutputStream; import java.io.IOException; +import java.util.ArrayList; +@ExposedType(name = "_ast.Break", base = PyObject.class) public class Break extends stmtType { +public static final PyType TYPE = PyType.fromClass(Break.class); public Break(Token token) { super(token); Modified: branches/astwrite/src/org/python/antlr/ast/Call.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/Call.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/ast/Call.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,22 +1,34 @@ // Autogenerated AST node package org.python.antlr.ast; -import java.util.ArrayList; import org.python.antlr.PythonTree; import org.python.antlr.adapter.AstAdapters; import org.python.antlr.adapter.ListWrapper; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; +import org.python.core.Py; +import org.python.core.PyObject; +import org.python.core.PyType; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedNew; +import org.python.expose.ExposedSet; +import org.python.expose.ExposedType; import java.io.DataOutputStream; import java.io.IOException; +import java.util.ArrayList; +@ExposedType(name = "_ast.Call", base = PyObject.class) public class Call extends exprType { +public static final PyType TYPE = PyType.fromClass(Call.class); private exprType func; public exprType getInternalFunc() { return func; } - public Object getFunc() { - return func; + @ExposedGet(name = "func") + public PyObject getFunc() { + return Py.None; } + @ExposedSet(name = "func") public void setFunc(Object func) { this.func = AstAdapters.to_expr(func); } @@ -25,31 +37,37 @@ public java.util.List<exprType> getInternalArgs() { return args; } - public Object getArgs() { - return new ListWrapper(args, AstAdapters.exprAdapter); + @ExposedGet(name = "args") + public PyObject getArgs() { + return Py.None; } + @ExposedSet(name = "args") public void setArgs(Object args) { - this.args = AstAdapters.to_exprList(args); + //FJW this.args = AstAdapters.to_exprList(args); } private java.util.List<keywordType> keywords; public java.util.List<keywordType> getInternalKeywords() { return keywords; } - public Object getKeywords() { - return new ListWrapper(keywords, AstAdapters.keywordAdapter); + @ExposedGet(name = "keywords") + public PyObject getKeywords() { + return Py.None; } + @ExposedSet(name = "keywords") public void setKeywords(Object keywords) { - this.keywords = AstAdapters.to_keywordList(keywords); + //FJW this.keywords = AstAdapters.to_keywordList(keywords); } private exprType starargs; public exprType getInternalStarargs() { return starargs; } - public Object getStarargs() { - return starargs; + @ExposedGet(name = "starargs") + public PyObject getStarargs() { + return Py.None; } + @ExposedSet(name = "starargs") public void setStarargs(Object starargs) { this.starargs = AstAdapters.to_expr(starargs); } @@ -58,9 +76,11 @@ public exprType getInternalKwargs() { return kwargs; } - public Object getKwargs() { - return kwargs; + @ExposedGet(name = "kwargs") + public PyObject getKwargs() { + return Py.None; } + @ExposedSet(name = "kwargs") public void setKwargs(Object kwargs) { this.kwargs = AstAdapters.to_expr(kwargs); } @@ -71,7 +91,15 @@ "starargs", "kwargs"}; public String[] get_fields() { return fields; } - public Call() {} + public Call() { + this(TYPE); + } + public Call(PyType subType) { + super(subType); + } + @ExposedNew + @ExposedMethod + public void Module___init__(PyObject[] args, String[] keywords) {} public Call(Object func, Object args, Object keywords, Object starargs, Object kwargs) { setFunc(func); Modified: branches/astwrite/src/org/python/antlr/ast/ClassDef.java =================================================================== --- branches/astwrite/src/org/python/antlr/ast/ClassDef.java 2008-11-29 00:48:32 UTC (rev 5659) +++ branches/astwrite/src/org/python/antlr/ast/ClassDef.java 2008-11-29 04:59:20 UTC (rev 5660) @@ -1,22 +1,34 @@ // Autogenerated AST node package org.python.antlr.ast; -import java.util.ArrayList; import org.python.antlr.PythonTree; import org.python.antlr.adapter.AstAdapters; import org.python.antlr.adapter.ListWrapper; import org.antlr.runtime.CommonToke... [truncated message content] |
From: <cg...@us...> - 2008-11-29 00:48:42
|
Revision: 5659 http://jython.svn.sourceforge.net/jython/?rev=5659&view=rev Author: cgroves Date: 2008-11-29 00:48:32 +0000 (Sat, 29 Nov 2008) Log Message: ----------- Assign the type on PyBeanProperty to the type returned by its getter and only use a setter if its parameter's type matches that. Push accesses to PyObject.javaProxy that query information from the proxy through getJavaProxy. This calls proxyInit if the proxy doesn't already exist which keeps things from blowing up if something accesses the javaProxy in an __init__. Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/IdImpl.java branches/newstyle-java-types/src/org/python/core/PyBeanProperty.java branches/newstyle-java-types/src/org/python/core/PyJavaType.java branches/newstyle-java-types/src/org/python/core/PyObject.java Modified: branches/newstyle-java-types/src/org/python/core/IdImpl.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/IdImpl.java 2008-11-29 00:17:40 UTC (rev 5658) +++ branches/newstyle-java-types/src/org/python/core/IdImpl.java 2008-11-29 00:48:32 UTC (rev 5659) @@ -66,7 +66,7 @@ public long id(PyObject o) { if (o.getType() instanceof PyJavaType) { - return java_obj_id(o.javaProxy); + return java_obj_id(o.getJavaProxy()); } else { return java_obj_id(o); } Modified: branches/newstyle-java-types/src/org/python/core/PyBeanProperty.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyBeanProperty.java 2008-11-29 00:17:40 UTC (rev 5658) +++ branches/newstyle-java-types/src/org/python/core/PyBeanProperty.java 2008-11-29 00:48:32 UTC (rev 5659) @@ -62,7 +62,7 @@ Object jvalue = Py.tojava(value, myType); try { - setMethod.invoke(iself, new Object[] {jvalue}); + setMethod.invoke(iself, jvalue); } catch (Exception e) { throw Py.JavaError(e); } Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-29 00:17:40 UTC (rev 5658) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-29 00:48:32 UTC (rev 5659) @@ -70,11 +70,12 @@ name = normalize(StringUtil.decapitalize(name)); PyBeanProperty prop = props.get(name); if (prop == null) { - prop = new PyBeanProperty(name, underlying_class, null, null); + prop = new PyBeanProperty(name, null, null, null); props.put(name, prop); } if (get) { prop.getMethod = meth; + prop.myType = meth.getReturnType(); } else { prop.setMethod = meth; } @@ -134,7 +135,7 @@ // If the return types on the set and get methods for a property don't agree, the get // get method takes precedence if (prop.getMethod != null && prop.setMethod != null - && prop.getMethod.getReturnType() != prop.setMethod.getReturnType()) { + && prop.myType != prop.setMethod.getParameterTypes()[0]) { prop.setMethod = null; } dict.__setitem__(prop.__name__, prop); @@ -225,7 +226,7 @@ new PyBuiltinMethodNarrow("__len__", 0, 0) { @Override public PyObject __call__() { - return Py.newInteger(((Collection<?>)self.javaProxy).size()); + return Py.newInteger(((Collection<?>)self.getJavaProxy()).size()); } }; @@ -233,7 +234,7 @@ new PyBuiltinMethodNarrow("__getitem__", 1, 1) { @Override public PyObject __call__(PyObject key) { - return Py.java2py(((Map<?, ?>)self.javaProxy).get(Py.tojava(key, Object.class))); + return Py.java2py(((Map<?, ?>)self.getJavaProxy()).get(Py.tojava(key, Object.class))); } }; @@ -241,7 +242,7 @@ new PyBuiltinMethodNarrow("__setitem__", 2, 2) { @Override public PyObject __call__(PyObject key, PyObject value) { - return Py.java2py(((Map<Object, Object>)self.javaProxy).put(Py.tojava(key, Object.class), + return Py.java2py(((Map<Object, Object>)self.getJavaProxy()).put(Py.tojava(key, Object.class), Py.tojava(value, Object.class))); } @@ -251,7 +252,7 @@ new PyBuiltinMethodNarrow("__delitem__", 1, 1) { @Override public PyObject __call__(PyObject key, PyObject value) { - return Py.java2py(((Map<?, ?>)self.javaProxy).remove(Py.tojava(key, Object.class))); + return Py.java2py(((Map<?, ?>)self.getJavaProxy()).remove(Py.tojava(key, Object.class))); } }; @@ -260,7 +261,7 @@ @Override public PyObject __call__(PyObject key) { if (key instanceof PyInteger) { - return Py.java2py(((List<?>)self.javaProxy).get(((PyInteger)key).getValue())); + return Py.java2py(((List<?>)self.getJavaProxy()).get(((PyInteger)key).getValue())); } else { throw Py.TypeError("only integer keys accepted"); } @@ -272,7 +273,7 @@ @Override public PyObject __call__(PyObject key, PyObject value) { if (key instanceof PyInteger) { - ((List<Object>)self.javaProxy).set(((PyInteger)key).getValue(), + ((List<Object>)self.getJavaProxy()).set(((PyInteger)key).getValue(), Py.tojava(value, Object.class)); } else { throw Py.TypeError("only integer keys accepted"); @@ -286,7 +287,7 @@ @Override public PyObject __call__(PyObject key, PyObject value) { if (key instanceof PyInteger) { - return Py.java2py(((List<Object>)self.javaProxy).remove(((PyInteger)key).getValue())); + return Py.java2py(((List<Object>)self.getJavaProxy()).remove(((PyInteger)key).getValue())); } else { throw Py.TypeError("only integer keys accepted"); } @@ -322,7 +323,7 @@ private static final PyBuiltinMethodNarrow ITERABLE_PROXY = new PyBuiltinMethodNarrow("__iter__", 0, 0) { public PyObject __call__() { - return new IteratorIter(((Iterable)self.javaProxy).iterator()); + return new IteratorIter(((Iterable)self.getJavaProxy()).iterator()); } }; @@ -330,8 +331,8 @@ new PyBuiltinMethodNarrow("__eq__", 1, 1) { @Override public PyObject __call__(PyObject o) { - return self.javaProxy.equals(o.__tojava__(self.javaProxy.getClass())) ? Py.True - : Py.False; + return self.getJavaProxy().equals(o.__tojava__(self.getJavaProxy().getClass())) ? + Py.True : Py.False; } }; Modified: branches/newstyle-java-types/src/org/python/core/PyObject.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-29 00:17:40 UTC (rev 5658) +++ branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-29 00:48:32 UTC (rev 5659) @@ -37,9 +37,12 @@ } - // This field is only filled on Python wrappers for Java objects and for Python subclasses of - // Java classes. - Object javaProxy; + /** + * An underlying Java instance that this object is wrapping or is a subclass of. Anything + * attempting to use the proxy should go through {@link #getJavaProxy()} which ensures that it's + * initialized. + */ + protected Object javaProxy; private PyType objtype; @@ -243,7 +246,7 @@ * @param c the Class to convert this <code>PyObject</code> to. **/ public Object __tojava__(Class<?> c) { - if ((c == Object.class || c == Serializable.class) && javaProxy != null) { + if ((c == Object.class || c == Serializable.class) && getJavaProxy() != null) { return javaProxy; } if (c.isInstance(this)) { @@ -255,12 +258,19 @@ c = tmp; } } - if (c.isInstance(javaProxy)) { + if (c.isInstance(getJavaProxy())) { return javaProxy; } return Py.NoConversion; } + protected Object getJavaProxy() { + if (javaProxy == null) { + proxyInit(); + } + return javaProxy; + } + private static final Map<Class<?>, Class<?>> primitiveMap = Generic.map(); static { primitiveMap.put(Character.TYPE, Character.class); @@ -1573,6 +1583,8 @@ * @return the result of the comparison **/ public PyObject _is(PyObject o) { + // Access javaProxy directly here as is is for object identity, and at best getJavaProxy + // will initialize a new object with a different identity return this == o || (javaProxy != null && javaProxy == o.javaProxy) ? Py.True : Py.False; } @@ -1583,6 +1595,8 @@ * @return the result of the comparison **/ public PyObject _isnot(PyObject o) { + // Access javaProxy directly here as is is for object identity, and at best getJavaProxy + // will initialize a new object with a different identity return this != o || javaProxy != o.javaProxy ? Py.True : Py.False; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-29 00:17:45
|
Revision: 5658 http://jython.svn.sourceforge.net/jython/?rev=5658&view=rev Author: cgroves Date: 2008-11-29 00:17:40 +0000 (Sat, 29 Nov 2008) Log Message: ----------- Only attempt proxyInitting if __init__ has been found and worked, and only actually init instances of PyProxy. Add an __init__ for all Java classes, even interfaces and abstract classes. Handle throwing type errors for uninstantiable classes in PyReflectedConstructor. Pass _is and _isnot through to the javaproxy == if javaproxy is around. This assumes a constant mapping between a given Java type and the PyType wrapping it, but I think that's safe. Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/Py.java branches/newstyle-java-types/src/org/python/core/PyArrayDerived.java branches/newstyle-java-types/src/org/python/core/PyBaseExceptionDerived.java branches/newstyle-java-types/src/org/python/core/PyBooleanDerived.java branches/newstyle-java-types/src/org/python/core/PyClassMethodDerived.java branches/newstyle-java-types/src/org/python/core/PyComplexDerived.java branches/newstyle-java-types/src/org/python/core/PyDictionaryDerived.java branches/newstyle-java-types/src/org/python/core/PyEnumerateDerived.java branches/newstyle-java-types/src/org/python/core/PyFileDerived.java branches/newstyle-java-types/src/org/python/core/PyFloatDerived.java branches/newstyle-java-types/src/org/python/core/PyFrozenSetDerived.java branches/newstyle-java-types/src/org/python/core/PyIntegerDerived.java branches/newstyle-java-types/src/org/python/core/PyJavaType.java branches/newstyle-java-types/src/org/python/core/PyListDerived.java branches/newstyle-java-types/src/org/python/core/PyLongDerived.java branches/newstyle-java-types/src/org/python/core/PyModuleDerived.java branches/newstyle-java-types/src/org/python/core/PyObject.java branches/newstyle-java-types/src/org/python/core/PyObjectDerived.java branches/newstyle-java-types/src/org/python/core/PyPropertyDerived.java branches/newstyle-java-types/src/org/python/core/PyReflectedConstructor.java branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java branches/newstyle-java-types/src/org/python/core/PySetDerived.java branches/newstyle-java-types/src/org/python/core/PySliceDerived.java branches/newstyle-java-types/src/org/python/core/PyStringDerived.java branches/newstyle-java-types/src/org/python/core/PySuperDerived.java branches/newstyle-java-types/src/org/python/core/PyTupleDerived.java branches/newstyle-java-types/src/org/python/core/PyTypeDerived.java branches/newstyle-java-types/src/org/python/core/PyUnicodeDerived.java branches/newstyle-java-types/src/org/python/modules/_collections/PyDefaultDictDerived.java branches/newstyle-java-types/src/org/python/modules/_collections/PyDequeDerived.java branches/newstyle-java-types/src/org/python/modules/_csv/PyDialectDerived.java branches/newstyle-java-types/src/org/python/modules/_functools/PyPartialDerived.java branches/newstyle-java-types/src/org/python/modules/_weakref/ReferenceTypeDerived.java branches/newstyle-java-types/src/org/python/modules/random/PyRandomDerived.java branches/newstyle-java-types/src/org/python/modules/thread/PyLocalDerived.java branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporterDerived.java branches/newstyle-java-types/src/templates/object.derived Removed Paths: ------------- branches/newstyle-java-types/src/org/python/core/CollectionIter.java Deleted: branches/newstyle-java-types/src/org/python/core/CollectionIter.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/CollectionIter.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/CollectionIter.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1,31 +0,0 @@ -// Copyright (c) Finn Bock -package org.python.core; - -import java.util.Enumeration; -import java.util.Iterator; - -class EnumerationIter extends PyIterator { - - private Enumeration<Object> proxy; - - public EnumerationIter(Enumeration<Object> proxy) { - this.proxy = proxy; - } - - public PyObject __iternext__() { - return proxy.hasMoreElements() ? Py.java2py(proxy.nextElement()) : null; - } -} - -class IteratorIter extends PyIterator { - - private Iterator<Object> proxy; - - public IteratorIter(Iterator<Object> proxy) { - this.proxy = proxy; - } - - public PyObject __iternext__() { - return proxy.hasNext() ? Py.java2py(proxy.next()) : null; - } -} Modified: branches/newstyle-java-types/src/org/python/core/Py.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/Py.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/Py.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -16,7 +16,6 @@ import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; -import java.util.HashSet; import java.util.Set; import org.python.antlr.ast.modType; @@ -24,6 +23,7 @@ import org.python.core.adapter.ClassicPyObjectAdapter; import org.python.core.adapter.ExtensiblePyObjectAdapter; import org.python.modules.errno; +import org.python.util.Generic; public final class Py { @@ -81,12 +81,13 @@ public static long TPFLAGS_HEAPTYPE; /** Builtin types that are used to setup PyObject. */ - static final Set<Class<?>> BOOTSTRAP_TYPES = new HashSet<Class<?>>(4); + static final Set<Class<?>> BOOTSTRAP_TYPES = Generic.set(); static { BOOTSTRAP_TYPES.add(PyObject.class); BOOTSTRAP_TYPES.add(PyType.class); BOOTSTRAP_TYPES.add(PyBuiltinCallable.class); BOOTSTRAP_TYPES.add(PyDataDescr.class); + BOOTSTRAP_TYPES.add(PyMethodDescr.class); } /** A unique object to indicate no conversion is possible Modified: branches/newstyle-java-types/src/org/python/core/PyArrayDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyArrayDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyArrayDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyBaseExceptionDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyBaseExceptionDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyBaseExceptionDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1067,9 +1067,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyBooleanDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyBooleanDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyBooleanDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyClassMethodDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyClassMethodDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyClassMethodDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyComplexDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyComplexDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyComplexDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyDictionaryDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyDictionaryDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyDictionaryDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyEnumerateDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyEnumerateDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyEnumerateDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyFileDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyFileDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyFileDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyFloatDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyFloatDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyFloatDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyFrozenSetDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyFrozenSetDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyFrozenSetDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyIntegerDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyIntegerDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyIntegerDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -6,6 +6,8 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collection; +import java.util.Enumeration; +import java.util.Iterator; import java.util.List; import java.util.Map; import org.python.core.util.StringUtil; @@ -137,27 +139,25 @@ } dict.__setitem__(prop.__name__, prop); } - Constructor<?>[] ctrs = underlying_class.getConstructors(); - if (ctrs.length != 0) { - final PyReflectedConstructor reflctr = new PyReflectedConstructor("_new_impl"); - for (Constructor<?> ctr : ctrs) { - reflctr.addConstructor(ctr); - } - if (PyObject.class.isAssignableFrom(underlying_class)) { - PyObject new_ = new PyNewWrapper(underlying_class, "__new__", -1, -1) { - public PyObject new_impl(boolean init, - PyType subtype, - PyObject[] args, - String[] keywords) { - return reflctr.make(args, keywords); - } - }; - dict.__setitem__("__new__", new_); - } else { - dict.__setitem__("__init__", reflctr); - } + final PyReflectedConstructor reflctr = new PyReflectedConstructor("_new_impl"); + for (Constructor<?> ctr : underlying_class.getConstructors()) { + reflctr.addConstructor(ctr); } + if (PyObject.class.isAssignableFrom(underlying_class)) { + PyObject new_ = new PyNewWrapper(underlying_class, "__new__", -1, -1) { + + public PyObject new_impl(boolean init, + PyType subtype, + PyObject[] args, + String[] keywords) { + return reflctr.make(args, keywords); + } + }; + dict.__setitem__("__new__", new_); + } else { + dict.__setitem__("__init__", reflctr); + } for (Class<?> inner : underlying_class.getClasses()) { dict.__setitem__(inner.getSimpleName(), PyType.fromClass(inner)); } @@ -292,7 +292,33 @@ } } }; + class EnumerationIter extends PyIterator { + private Enumeration<Object> proxy; + + public EnumerationIter(Enumeration<Object> proxy) { + this.proxy = proxy; + } + + public PyObject __iternext__() { + return proxy.hasMoreElements() ? Py.java2py(proxy.nextElement()) : null; + } + } + + private static class IteratorIter extends PyIterator { + + private Iterator<Object> proxy; + + public IteratorIter(Iterator<Object> proxy) { + this.proxy = proxy; + } + + public PyObject __iternext__() { + return proxy.hasNext() ? Py.java2py(proxy.next()) : null; + } + } + + private static final PyBuiltinMethodNarrow ITERABLE_PROXY = new PyBuiltinMethodNarrow("__iter__", 0, 0) { public PyObject __call__() { Modified: branches/newstyle-java-types/src/org/python/core/PyListDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyListDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyListDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyLongDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyLongDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyLongDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyModuleDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyModuleDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyModuleDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1067,9 +1067,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyObject.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -2,7 +2,6 @@ package org.python.core; import java.io.Serializable; -import java.lang.reflect.Modifier; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; @@ -103,9 +102,7 @@ /** * Dispatch __init__ behavior */ - public void dispatch__init__(PyType type,PyObject[] args,String[] keywords) { - proxyInit(); - } + public void dispatch__init__(PyType type, PyObject[] args, String[] keywords) {} /** * Attempts to automatically initialize our Java proxy if we have one and it wasn't initialized @@ -116,11 +113,8 @@ if (javaProxy != null || c == null) { return; } - int mods = c.getModifiers(); - if (Modifier.isInterface(mods)) { - throw Py.TypeError("can't instantiate interface (" + c.getName() + ")"); - } else if (Modifier.isAbstract(mods)) { - throw Py.TypeError("can't instantiate abstract class (" + c.getName() + ")"); + if (!PyProxy.class.isAssignableFrom(c)) { + throw Py.SystemError("Automatic proxy initialization should only occur on proxy classes"); } PyProxy proxy; ThreadState ts = Py.getThreadState(); @@ -1579,7 +1573,7 @@ * @return the result of the comparison **/ public PyObject _is(PyObject o) { - return this == o ? Py.True : Py.False; + return this == o || (javaProxy != null && javaProxy == o.javaProxy) ? Py.True : Py.False; } /** @@ -1589,7 +1583,7 @@ * @return the result of the comparison **/ public PyObject _isnot(PyObject o) { - return this != o ? Py.True : Py.False; + return this != o || javaProxy != o.javaProxy ? Py.True : Py.False; } /** Modified: branches/newstyle-java-types/src/org/python/core/PyObjectDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyObjectDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyObjectDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -712,7 +712,7 @@ if (impl!=null) { PyObject res=impl.__get__(this,self_type).__call__(); if (res instanceof PyInteger||res instanceof PyLong) - return(PyObject)res; + return res; throw Py.TypeError("__int__"+" should return an integer"); } return super.__int__(); @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyPropertyDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyPropertyDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyPropertyDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyReflectedConstructor.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyReflectedConstructor.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyReflectedConstructor.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -10,53 +10,48 @@ public PyReflectedConstructor(String name) { super(name); - __name__ = name; - argslist = new ReflectedArgs[1]; - nargs = 0; } - public PyReflectedConstructor(Constructor c) { + public PyReflectedConstructor(Constructor<?> c) { this(c.getDeclaringClass().getName()); addConstructor(c); } - private ReflectedArgs makeArgs(Constructor m) { + private ReflectedArgs makeArgs(Constructor<?> m) { return new ReflectedArgs(m, m.getParameterTypes(), m.getDeclaringClass(), true); } - public void addConstructor(Constructor m) { + public void addConstructor(Constructor<?> m) { int mods = m.getModifiers(); // Only add public methods unless we're overriding - if (!Modifier.isPublic(mods) && Options.respectJavaAccessibility) + if (!Modifier.isPublic(mods) && Options.respectJavaAccessibility) { return; + } addArgs(makeArgs(m)); } // xxx temporary solution, type ctr will go through __new__ ... PyObject make(PyObject[] args, String[] keywords) { - ReflectedArgs[] argsl = argslist; ReflectedCallData callData = new ReflectedCallData(); Object method = null; boolean consumes_keywords = false; - int nkeywords = keywords.length; PyObject[] allArgs = null; // Check for a matching constructor to call if (nargs > 0) { // PyArgsKeywordsCall signature, if present, is the first - if (argsl[0].matches(null, args, keywords, callData)) { - method = argsl[0].data; - consumes_keywords = argsl[0].flags == ReflectedArgs.PyArgsKeywordsCall; + if (argslist[0].matches(null, args, keywords, callData)) { + method = argslist[0].data; + consumes_keywords = argslist[0].flags == ReflectedArgs.PyArgsKeywordsCall; } else { allArgs = args; int i = 1; - if (nkeywords > 0) { - args = new PyObject[allArgs.length - nkeywords]; + if (keywords.length > 0) { + args = new PyObject[allArgs.length - keywords.length]; System.arraycopy(allArgs, 0, args, 0, args.length); i = 0; } for (; i < nargs; i++) { - ReflectedArgs rargs = argsl[i]; - if (rargs.matches(null, args, Py.NoKeywords, callData)) { - method = rargs.data; + if (argslist[i].matches(null, args, Py.NoKeywords, callData)) { + method = argslist[i].data; break; } } @@ -67,7 +62,7 @@ throwError(callData.errArg, args.length, true /* xxx? */, false); } // Do the actual constructor call - PyObject obj = null; + PyObject obj; try { obj = (PyObject)((Constructor<?>)method).newInstance(callData.getArgsArray()); } catch (Throwable t) { @@ -75,7 +70,7 @@ } if (!consumes_keywords) { int offset = args.length; - for (int i = 0; i < nkeywords; i++) { + for (int i = 0; i < keywords.length; i++) { obj.__setattr__(keywords[i], allArgs[i + offset]); } } @@ -87,12 +82,13 @@ throw Py.TypeError("invalid self argument to constructor"); } Class<?> javaClass = self.getType().getProxyType(); - + if (nargs == 0) { + throw Py.TypeError("No visible constructors for class (" + javaClass.getName() + ")"); + } Class<?> declaringClass = argslist[0].declaringClass; if (!declaringClass.isAssignableFrom(javaClass)) { throw Py.TypeError("self invalid - must implement: " + declaringClass.getName()); } - // If the declaring class is a pure Java type but we're instantiating a Python proxy, // grab the proxy version of the constructor to instantiate the proper type if (!PyProxy.class.isAssignableFrom(declaringClass) @@ -100,6 +96,12 @@ return PyType.fromClass(javaClass).lookup("__init__").__call__(self, args, keywords); } + int mods = declaringClass.getModifiers(); + if (Modifier.isInterface(mods)) { + throw Py.TypeError("can't instantiate interface (" + declaringClass.getName() + ")"); + } else if (Modifier.isAbstract(mods)) { + throw Py.TypeError("can't instantiate abstract class (" + declaringClass.getName() + ")"); + } if (self.javaProxy != null) { Class<?> sup = javaClass; if (PyProxy.class.isAssignableFrom(sup)) { @@ -131,7 +133,6 @@ } // Do the actual constructor call constructProxy(self, (Constructor<?>)method, callData.getArgsArray(), javaClass); - // Do setattr's for keyword args int offset = args.length; for (int i = 0; i < nkeywords; i++) { Modified: branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -7,23 +7,28 @@ import org.python.util.Generic; +public class PyReflectedFunction extends PyObject { -public class PyReflectedFunction extends PyObject -{ public String __name__; + public PyObject __doc__ = Py.None; - public ReflectedArgs[] argslist; + + public ReflectedArgs[] argslist = new ReflectedArgs[1]; + public int nargs; - public PyReflectedFunction(String name) { + protected PyReflectedFunction(String name) { __name__ = name; - argslist = new ReflectedArgs[1]; - nargs = 0; } public PyReflectedFunction(Method method) { this(method.getName()); addMethod(method); + if (nargs == 0) { + String msg = String.format("Attempted to make Java method visible, but it isn't " + + "callable[method=%s, class=%s]", method.getName(), method.getDeclaringClass()); + throw Py.SystemError(msg); + } } public PyObject _doget(PyObject container) { @@ -31,13 +36,14 @@ } public PyObject _doget(PyObject container, PyObject wherefound) { - if (container == null) + if (container == null) { return this; + } return new PyMethod(this, container, wherefound); } public boolean _doset(PyObject container) { - throw Py.TypeError("java function not settable: "+__name__); + throw Py.TypeError("java function not settable: " + __name__); } public PyObject getDoc() { @@ -45,7 +51,8 @@ } private ReflectedArgs makeArgs(Method m) { - return new ReflectedArgs(m, m.getParameterTypes(), + return new ReflectedArgs(m, + m.getParameterTypes(), m.getDeclaringClass(), Modifier.isStatic(m.getModifiers())); } @@ -64,63 +71,54 @@ } protected boolean handles(ReflectedArgs args) { - ReflectedArgs[] argsl = argslist; - int n = nargs; - for(int i=0; i<n; i++) { - int cmp = args.compareTo(argsl[i]); - if (cmp == 0) + for (int i = 0; i < nargs; i++) { + int cmp = args.compareTo(argslist[i]); + if (cmp == 0) { return true; - if (cmp == +1) + } else if (cmp == 1) { return false; + } } return false; } public void addMethod(Method m) { - int mods = m.getModifiers(); // Only add public methods unless we're overriding - if (!Modifier.isPublic(mods) && Options.respectJavaAccessibility) + if (!Modifier.isPublic(m.getModifiers()) && Options.respectJavaAccessibility) { return; + } addArgs(makeArgs(m)); } protected void addArgs(ReflectedArgs args) { - ReflectedArgs[] argsl = argslist; - int n = nargs; int i; - for(i=0; i<n; i++) { - int cmp = args.compareTo(argsl[i]); - if (cmp == 0) + for (i = 0; i < nargs; i++) { + int cmp = args.compareTo(argslist[i]); + if (cmp == 0) { return; - if (cmp == ReflectedArgs.REPLACE) { - argsl[i] = args; + } else if (cmp == ReflectedArgs.REPLACE) { + argslist[i] = args; return; - } - if (cmp == -1) + } else if (cmp == -1) { break; + } } - - int nn = n+1; - if (nn > argsl.length) { - argsl = new ReflectedArgs[nn+2]; - System.arraycopy(argslist, 0, argsl, 0, n); - argslist = argsl; + int nn = nargs + 1; + if (nn > argslist.length) { + ReflectedArgs[] newargslist = new ReflectedArgs[nn + 2]; + System.arraycopy(argslist, 0, newargslist, 0, nargs); + argslist = newargslist; } - - for(int j=n; j>i; j--) { - argsl[j] = argsl[j-1]; + for (int j = nargs; j > i; j--) { + argslist[j] = argslist[j - 1]; } - - argsl[i] = args; + argslist[i] = args; nargs = nn; } - public PyObject __call__(PyObject self, PyObject[] args, - String[] keywords) - { + public PyObject __call__(PyObject self, PyObject[] args, String[] keywords) { ReflectedCallData callData = new ReflectedCallData(); Object method = null; - ReflectedArgs[] argsl = argslist; int n = nargs; for (int i = 0; i < n; i++) { @@ -132,19 +130,17 @@ } } if (method == null) { - throwError(callData.errArg, args.length, self != null, - keywords.length != 0); + throwError(callData.errArg, args.length, self != null, keywords.length != 0); } - Object cself = callData.self; Method m = (Method)method; + Object o; try { - - Object o = m.invoke(cself, callData.getArgsArray()); - return Py.java2py(o); + o = m.invoke(cself, callData.getArgsArray()); } catch (Throwable t) { throw Py.JavaError(t); } + return Py.java2py(o); } public PyObject __call__(PyObject[] args, String[] keywords) { @@ -152,59 +148,49 @@ } // A bunch of code to make error handling prettier - - protected void throwError(String message) { - throw Py.TypeError(__name__+"(): "+message); + throw Py.TypeError(__name__ + "(): " + message); } - private static void addRange(StringBuffer buf, int min, int max, - String sep) - { + private static void addRange(StringBuilder buf, int min, int max, String sep) { if (buf.length() > 0) { buf.append(sep); } if (min < max) { - buf.append(Integer.toString(min)+"-"+max); + buf.append(Integer.toString(min)).append('-').append(max); } else { buf.append(min); } } - protected void throwArgCountError(int nArgs, boolean self) { // Assume no argument lengths greater than 40... boolean[] legalArgs = new boolean[40]; int maxArgs = -1; int minArgs = 40; - - ReflectedArgs[] argsl = argslist; - int n = nargs; - for (int i=0; i<n; i++) { - ReflectedArgs rargs = argsl[i]; - + for (int i = 0; i < nargs; i++) { + ReflectedArgs rargs = argslist[i]; int l = rargs.args.length; if (!self && !rargs.isStatic) { l += 1; } - legalArgs[l] = true; - if (l > maxArgs) + if (l > maxArgs) { maxArgs = l; - if (l < minArgs) + } + if (l < minArgs) { minArgs = l; + } } - - StringBuffer buf = new StringBuffer(); - + StringBuilder buf = new StringBuilder(); int startRange = minArgs; - int a = minArgs+1; + int a = minArgs + 1; while (a < maxArgs) { if (legalArgs[a]) { a++; continue; } else { - addRange(buf, startRange, a-1, ", "); + addRange(buf, startRange, a - 1, ", "); a++; while (a <= maxArgs) { if (legalArgs[a]) { @@ -216,21 +202,21 @@ } } addRange(buf, startRange, maxArgs, " or "); - throwError("expected "+buf+" args; got "+nArgs); + throwError("expected " + buf + " args; got " + nArgs); } private static String ordinal(int n) { - switch(n+1) { - case 0: - return "self"; - case 1: - return "1st"; - case 2: - return "2nd"; - case 3: - return "3rd"; - default: - return Integer.toString(n+1)+"th"; + switch(n + 1){ + case 0: + return "self"; + case 1: + return "1st"; + case 2: + return "2nd"; + case 3: + return "3rd"; + default: + return Integer.toString(n + 1) + "th"; } } @@ -239,7 +225,7 @@ return "String"; } if (arg.isArray()) { - return niceName(arg.getComponentType())+"[]"; + return niceName(arg.getComponentType()) + "[]"; } return arg.getName(); } @@ -264,10 +250,9 @@ buf.append(niceName(arg)); buf.append(", "); } - if(buf.length() > 2) { + if (buf.length() > 2) { buf.setLength(buf.length() - 2); } - throwError(ordinal(errArg) + " arg can't be coerced to " + buf); } @@ -283,16 +268,15 @@ // Included only for debugging purposes... public void printArgs() { - System.err.println("nargs: "+nargs); - for(int i=0; i<nargs; i++) { + System.err.println("nargs: " + nargs); + for (int i = 0; i < nargs; i++) { ReflectedArgs args = argslist[i]; System.err.println(args.toString()); } } - public String toString() { - //printArgs(); - return "<java function "+__name__+" "+Py.idstr(this)+">"; + // printArgs(); + return "<java function " + __name__ + " " + Py.idstr(this) + ">"; } } Modified: branches/newstyle-java-types/src/org/python/core/PySetDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PySetDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PySetDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PySliceDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PySliceDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PySliceDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyStringDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyStringDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyStringDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PySuperDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PySuperDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PySuperDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyTupleDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyTupleDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyTupleDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyTypeDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyTypeDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyTypeDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1067,9 +1067,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/core/PyUnicodeDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyUnicodeDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/core/PyUnicodeDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1091,9 +1091,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/_collections/PyDefaultDictDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/_collections/PyDefaultDictDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/modules/_collections/PyDefaultDictDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1093,9 +1093,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/_collections/PyDequeDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/_collections/PyDequeDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/modules/_collections/PyDequeDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1093,9 +1093,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/_csv/PyDialectDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/_csv/PyDialectDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/modules/_csv/PyDialectDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1069,9 +1069,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/_functools/PyPartialDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/_functools/PyPartialDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/modules/_functools/PyPartialDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1069,9 +1069,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/_weakref/ReferenceTypeDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1093,9 +1093,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/random/PyRandomDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/random/PyRandomDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/modules/random/PyRandomDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1093,9 +1093,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/thread/PyLocalDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/thread/PyLocalDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/modules/thread/PyLocalDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1069,9 +1069,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporterDerived.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporterDerived.java 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporterDerived.java 2008-11-29 00:17:40 UTC (rev 5658) @@ -1069,9 +1069,9 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { Modified: branches/newstyle-java-types/src/templates/object.derived =================================================================== --- branches/newstyle-java-types/src/templates/object.derived 2008-11-28 21:53:04 UTC (rev 5657) +++ branches/newstyle-java-types/src/templates/object.derived 2008-11-29 00:17:40 UTC (rev 5658) @@ -426,9 +426,9 @@ throw Py.TypeError(String.format("__init__() should return None, not '%.200s'", res.getType().fastGetName())); } + proxyInit(); } } - proxyInit(); } public PyObject __index__() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-28 21:54:18
|
Revision: 5657 http://jython.svn.sourceforge.net/jython/?rev=5657&view=rev Author: cgroves Date: 2008-11-28 21:53:04 +0000 (Fri, 28 Nov 2008) Log Message: ----------- More cleanup Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/PyJavaType.java Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-28 21:29:14 UTC (rev 5656) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-28 21:53:04 UTC (rev 5657) @@ -2,6 +2,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; +import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collection; @@ -33,95 +34,103 @@ @Override protected void fillDict() { dict = new PyStringMap(); + Class<?> base = underlying_class.getSuperclass(); + + // Add methods and determine bean properties declared on this class Map<String, PyBeanProperty> props = Generic.map(); - Class<?> base = underlying_class.getSuperclass(); - Method[] methods = underlying_class.getMethods(); - for (Method meth : methods) { - Class<?> declaring = meth.getDeclaringClass(); - if (base == null || - (declaring != base && base.isAssignableFrom(declaring) && !ignore(meth))) { - String methname = meth.getName(); - String nmethname = normalize_name(methname); - PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); - if (reflfunc == null) { - dict.__setitem__(nmethname, new PyReflectedFunction(meth)); - } else { - reflfunc.addMethod(meth); + for (Method meth : underlying_class.getMethods()) { + if (!declaredOnMember(base, meth) || ignore(meth)) { + continue; + } + String methname = meth.getName(); + String nmethname = normalize(methname); + PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); + if (reflfunc == null) { + dict.__setitem__(nmethname, new PyReflectedFunction(meth)); + } else { + reflfunc.addMethod(meth); + } + if (!Modifier.isStatic(meth.getModifiers())) { + // check for xxxX.* + int n = meth.getParameterTypes().length; + String name = null; + boolean get = true; + if (methname.startsWith("get") && methname.length() > 3 && n == 0) { + name = methname.substring(3); + } else if (methname.startsWith("is") && methname.length() > 2 && n == 0 + && meth.getReturnType() == Boolean.TYPE) { + name = methname.substring(2); + } else if (methname.startsWith("set") && methname.length() > 3 && n == 1) { + name = methname.substring(3); + get = false; } - if (!Modifier.isStatic(meth.getModifiers())) { - // check for xxxX.* - int n = meth.getParameterTypes().length; - String name = null; - boolean get = true; - if (methname.startsWith("get") && methname.length() > 3 && n == 0) { - name = methname.substring(3); - } else if (methname.startsWith("is") && methname.length() > 2 && n == 0 - && meth.getReturnType() == Boolean.TYPE) { - name = methname.substring(2); - } else if (methname.startsWith("set") && methname.length() > 3 && n == 1) { - name = methname.substring(3); - get = false; + if (name != null) { + name = normalize(StringUtil.decapitalize(name)); + PyBeanProperty prop = props.get(name); + if (prop == null) { + prop = new PyBeanProperty(name, underlying_class, null, null); + props.put(name, prop); } - if (name != null) { - name = normalize_name(StringUtil.decapitalize(name)); - PyBeanProperty prop = props.get(name); - if (prop == null) { - prop = new PyBeanProperty(name, underlying_class, null, null); - props.put(name, prop); - } - if (get) { - prop.getMethod = meth; - } else { - prop.setMethod = meth; - } + if (get) { + prop.getMethod = meth; + } else { + prop.setMethod = meth; } } } } - for (Method meth : methods) { - String nmethname = normalize_name(meth.getName()); + + // Add arguments for superclass methods with the same names as methods declared on this type + for (Method meth : underlying_class.getMethods()) { + String nmethname = normalize(meth.getName()); PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); if (reflfunc != null) { reflfunc.addMethod(meth); } } - Field[] fields = underlying_class.getFields(); - for (Field field : fields) { - Class<?> declaring = field.getDeclaringClass(); - if (base == null || (declaring != base && base.isAssignableFrom(declaring))) { - String fldname = field.getName(); - int fldmods = field.getModifiers(); - Class<?> fldtype = field.getType(); - if (Modifier.isStatic(fldmods)) { - if (fldname.startsWith("__doc__") && fldname.length() > 7 - && fldtype == PyString.class) { - String fname = fldname.substring(7).intern(); - PyObject memb = dict.__finditem__(fname); - if (memb != null && memb instanceof PyReflectedFunction) { - PyString doc = null; - try { - doc = (PyString)field.get(null); - } catch (IllegalAccessException e) { - throw error(e); - } - ((PyReflectedFunction)memb).__doc__ = doc; + + // Add fields declared on this type + for (Field field : underlying_class.getFields()) { + if (!declaredOnMember(base, field)) { + continue; + } + String fldname = field.getName(); + if (Modifier.isStatic(field.getModifiers())) { + if (fldname.startsWith("__doc__") && fldname.length() > 7 + && field.getType() == PyString.class) { + String fname = fldname.substring(7).intern(); + PyObject memb = dict.__finditem__(fname); + if (memb != null && memb instanceof PyReflectedFunction) { + PyString doc = null; + try { + doc = (PyString)field.get(null); + } catch (IllegalAccessException e) { + throw Py.JavaError(e); } + ((PyReflectedFunction)memb).__doc__ = doc; } } - if (dict.__finditem__(normalize_name(fldname)) == null) { - dict.__setitem__(normalize_name(fldname), new PyReflectedField(field)); - } } + if (dict.__finditem__(normalize(fldname)) == null) { + dict.__setitem__(normalize(fldname), new PyReflectedField(field)); + } } + + // Fill in the bean properties picked up while going through the methods for (PyBeanProperty prop : props.values()) { PyObject prev = dict.__finditem__(prop.__name__); - if (prev != null && (!(prev instanceof PyReflectedField) - || !Modifier.isStatic(((PyReflectedField)prev).field.getModifiers()))) { - continue; - } if (prev != null) { - prop.field = ((PyReflectedField)prev).field; + if (!(prev instanceof PyReflectedField) + || !Modifier.isStatic(((PyReflectedField)prev).field.getModifiers())) { + // Any methods or non-static fields take precedence over the bean property + continue; + } else { + // Must've been a static field, so add it to the property + prop.field = ((PyReflectedField)prev).field; + } } + // If the return types on the set and get methods for a property don't agree, the get + // get method takes precedence if (prop.getMethod != null && prop.setMethod != null && prop.getMethod.getReturnType() != prop.setMethod.getReturnType()) { prop.setMethod = null; @@ -166,39 +175,37 @@ Method m = underlying_class.getMethod("classDictInit", PyObject.class); m.invoke(null, dict); } catch (Exception exc) { - throw error(exc); + throw Py.JavaError(exc); } } if (base != Object.class) { - has_set = get_descr_method(underlying_class, "__set__", OO) != null - || get_descr_method(underlying_class, "_doset", OO) != null; - has_delete = get_descr_method(underlying_class, "__delete__", PyObject.class) != null - || get_descr_method(underlying_class, "_dodel", PyObject.class) != null; + has_set = getDescrMethod(underlying_class, "__set__", OO) != null + || getDescrMethod(underlying_class, "_doset", OO) != null; + has_delete = getDescrMethod(underlying_class, "__delete__", PyObject.class) != null + || getDescrMethod(underlying_class, "_dodel", PyObject.class) != null; } } - private static String normalize_name(String name) { + private static boolean declaredOnMember(Class<?> base, Member declaring) { + return base == null || (declaring.getDeclaringClass() != base && + base.isAssignableFrom(declaring.getDeclaringClass())); + } + + private static String normalize(String name) { if (name.endsWith("$")) { name = name.substring(0, name.length() - 1); } return name.intern(); } - private static Method get_non_static_method(Class<?> c, String name, Class<?>... parmtypes) { + private static Method getDescrMethod(Class<?> c, String name, Class<?>... parmtypes) { + Method meth; try { - Method meth = c.getMethod(name, parmtypes); - if (!Modifier.isStatic(meth.getModifiers())) { - return meth; - } + meth = c.getMethod(name, parmtypes); } catch (NoSuchMethodException e) { - // ok + return null; } - return null; - } - - private static Method get_descr_method(Class<?> c, String name, Class<?>... parmtypes) { - Method meth = get_non_static_method(c, name, parmtypes); - if (meth != null && meth.getDeclaringClass() != PyObject.class) { + if (!Modifier.isStatic(meth.getModifiers()) && meth.getDeclaringClass() != PyObject.class) { return meth; } return null; @@ -214,11 +221,7 @@ return false; } - private static PyException error(Exception e) { - return Py.JavaError(e); - } - - protected static final PyBuiltinMethodNarrow LEN_PROXY = + private static final PyBuiltinMethodNarrow LEN_PROXY = new PyBuiltinMethodNarrow("__len__", 0, 0) { @Override public PyObject __call__() { @@ -226,7 +229,7 @@ } }; - protected static final PyBuiltinMethodNarrow MAP_GET_PROXY = + private static final PyBuiltinMethodNarrow MAP_GET_PROXY = new PyBuiltinMethodNarrow("__getitem__", 1, 1) { @Override public PyObject __call__(PyObject key) { @@ -234,7 +237,7 @@ } }; - protected static final PyBuiltinMethodNarrow MAP_PUT_PROXY = + private static final PyBuiltinMethodNarrow MAP_PUT_PROXY = new PyBuiltinMethodNarrow("__setitem__", 2, 2) { @Override public PyObject __call__(PyObject key, PyObject value) { @@ -244,7 +247,7 @@ } }; - protected static final PyBuiltinMethodNarrow MAP_REMOVE_PROXY = + private static final PyBuiltinMethodNarrow MAP_REMOVE_PROXY = new PyBuiltinMethodNarrow("__delitem__", 1, 1) { @Override public PyObject __call__(PyObject key, PyObject value) { @@ -252,7 +255,7 @@ } }; - protected static final PyBuiltinMethodNarrow LIST_GET_PROXY = + private static final PyBuiltinMethodNarrow LIST_GET_PROXY = new PyBuiltinMethodNarrow("__getitem__", 1, 1){ @Override public PyObject __call__(PyObject key) { @@ -264,7 +267,7 @@ } }; - protected static final PyBuiltinMethodNarrow LIST_SET_PROXY = + private static final PyBuiltinMethodNarrow LIST_SET_PROXY = new PyBuiltinMethodNarrow("__setitem__", 2, 2) { @Override public PyObject __call__(PyObject key, PyObject value) { @@ -278,7 +281,7 @@ } }; - protected static final PyBuiltinMethodNarrow LIST_REMOVE_PROXY = + private static final PyBuiltinMethodNarrow LIST_REMOVE_PROXY = new PyBuiltinMethodNarrow("__delitem__", 1, 1) { @Override public PyObject __call__(PyObject key, PyObject value) { @@ -290,14 +293,14 @@ } }; - public static final PyBuiltinMethodNarrow ITERABLE_PROXY = + private static final PyBuiltinMethodNarrow ITERABLE_PROXY = new PyBuiltinMethodNarrow("__iter__", 0, 0) { public PyObject __call__() { return new IteratorIter(((Iterable)self.javaProxy).iterator()); } }; - public static final PyBuiltinMethodNarrow EQUALS_PROXY = + private static final PyBuiltinMethodNarrow EQUALS_PROXY = new PyBuiltinMethodNarrow("__eq__", 1, 1) { @Override public PyObject __call__(PyObject o) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-28 21:29:17
|
Revision: 5656 http://jython.svn.sourceforge.net/jython/?rev=5656&view=rev Author: cgroves Date: 2008-11-28 21:29:14 +0000 (Fri, 28 Nov 2008) Log Message: ----------- Simplify PyBeanProperty construction Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/PyJavaType.java Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-28 21:10:39 UTC (rev 5655) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-28 21:29:14 UTC (rev 5656) @@ -5,10 +5,8 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collection; -import java.util.HashMap; import java.util.List; import java.util.Map; - import org.python.core.util.StringUtil; import org.python.expose.ExposeAsSuperclass; import org.python.util.Generic; @@ -35,7 +33,7 @@ @Override protected void fillDict() { dict = new PyStringMap(); - Map<String, Object> propnames = new HashMap<String, Object>(); + Map<String, PyBeanProperty> props = Generic.map(); Class<?> base = underlying_class.getSuperclass(); Method[] methods = underlying_class.getMethods(); for (Method meth : methods) { @@ -53,14 +51,30 @@ if (!Modifier.isStatic(meth.getModifiers())) { // check for xxxX.* int n = meth.getParameterTypes().length; - if (methname.startsWith("get") && n == 0) { - propnames.put(methname.substring(3), "getter"); - } else if (methname.startsWith("is") && n == 0 + String name = null; + boolean get = true; + if (methname.startsWith("get") && methname.length() > 3 && n == 0) { + name = methname.substring(3); + } else if (methname.startsWith("is") && methname.length() > 2 && n == 0 && meth.getReturnType() == Boolean.TYPE) { - propnames.put(methname.substring(2), "getter"); - } else if (methname.startsWith("set") && n == 1) { - propnames.put(methname.substring(3), meth); + name = methname.substring(2); + } else if (methname.startsWith("set") && methname.length() > 3 && n == 1) { + name = methname.substring(3); + get = false; } + if (name != null) { + name = normalize_name(StringUtil.decapitalize(name)); + PyBeanProperty prop = props.get(name); + if (prop == null) { + prop = new PyBeanProperty(name, underlying_class, null, null); + props.put(name, prop); + } + if (get) { + prop.getMethod = meth; + } else { + prop.setMethod = meth; + } + } } } } @@ -99,41 +113,20 @@ } } } - for (String propname : propnames.keySet()) { - if (propname.equals("")) { + for (PyBeanProperty prop : props.values()) { + PyObject prev = dict.__finditem__(prop.__name__); + if (prev != null && (!(prev instanceof PyReflectedField) + || !Modifier.isStatic(((PyReflectedField)prev).field.getModifiers()))) { continue; } - String npropname = normalize_name(StringUtil.decapitalize(propname)); - PyObject prev = dict.__finditem__(npropname); - if (prev != null && (!(prev instanceof PyReflectedField) || - !Modifier.isStatic(((PyReflectedField)prev).field.getModifiers()))) { - continue; + if (prev != null) { + prop.field = ((PyReflectedField)prev).field; } - Method getter = null; - Method setter = null; - Class<?> proptype = null; - getter = get_non_static_method(underlying_class, "get" + propname); - if (getter == null) - getter = get_non_static_method(underlying_class, "is" + propname); - if (getter != null) { - proptype = getter.getReturnType(); - setter = get_non_static_method(underlying_class, "set" + propname, proptype); - } else { - Object o = propnames.get(propname); - if (o instanceof Method) { - setter = (Method)o; - proptype = setter.getParameterTypes()[0]; - } + if (prop.getMethod != null && prop.setMethod != null + && prop.getMethod.getReturnType() != prop.setMethod.getReturnType()) { + prop.setMethod = null; } - if (setter != null || getter != null) { - PyBeanProperty prop = new PyBeanProperty(npropname, proptype, getter, setter); - if (prev != null) { - prop.field = ((PyReflectedField)prev).field; - } - dict.__setitem__(npropname, prop); - } else { - // XXX error - } + dict.__setitem__(prop.__name__, prop); } Constructor<?>[] ctrs = underlying_class.getConstructors(); if (ctrs.length != 0) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-28 21:10:45
|
Revision: 5655 http://jython.svn.sourceforge.net/jython/?rev=5655&view=rev Author: pjenvey Date: 2008-11-28 21:10:39 +0000 (Fri, 28 Nov 2008) Log Message: ----------- have exposed methods and fields convert null Strings results to Py.None Modified Paths: -------------- trunk/jython/src/org/python/expose/generate/Exposer.java trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.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/Exposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/Exposer.java 2008-11-28 10:06:54 UTC (rev 5654) +++ trunk/jython/src/org/python/expose/generate/Exposer.java 2008-11-28 21:10:39 UTC (rev 5655) @@ -5,6 +5,7 @@ import org.python.objectweb.asm.ClassVisitor; import org.python.objectweb.asm.ClassWriter; +import org.python.objectweb.asm.Label; import org.python.objectweb.asm.MethodVisitor; import org.python.objectweb.asm.Opcodes; import org.python.objectweb.asm.Type; @@ -228,7 +229,16 @@ if(inputType.equals(VOID)) { getStatic(PY, "None", PYOBJ); } else if(inputType.equals(STRING)) { + Label newString = new Label(); + Label end = new Label(); + mv.visitInsn(DUP); + mv.visitJumpInsn(IFNONNULL, newString); + mv.visitInsn(POP); + getStatic(PY, "None", PYOBJ); + mv.visitJumpInsn(GOTO, end); + mv.visitLabel(newString); callStatic(PY, "newString", PYSTR, STRING); + mv.visitLabel(end); } else if(inputType.equals(BOOLEAN)) { callStatic(PY, "newBoolean", PYBOOLEAN, BOOLEAN); } else if(inputType.equals(INT) || inputType.equals(BYTE) || inputType.equals(SHORT)) { Modified: trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java 2008-11-28 10:06:54 UTC (rev 5654) +++ trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java 2008-11-28 21:10:39 UTC (rev 5655) @@ -76,7 +76,17 @@ assertFalse(instance.implementsDescrSet()); assertFalse(instance.implementsDescrDelete()); } + + public void testNullReturns() throws Exception { + PyDataDescr instance = makeDescriptor(new DescSetup() { + public void setup(DescriptorExposer de) { + de.addFieldGetter("nullString", STRING); + } + }); + assertEquals(Py.None, instance.__get__(se, PY_TYPE)); + } + public void testMethodSetter() throws Exception { PyDataDescr instance = makeDescriptor(new DescSetup() { @@ -224,5 +234,7 @@ public boolean bool; public String toStringVal = SimpleExposed.TO_STRING_RETURN; + + public String nullString = null; } } Modified: trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java 2008-11-28 10:06:54 UTC (rev 5654) +++ trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java 2008-11-28 21:10:39 UTC (rev 5655) @@ -18,7 +18,7 @@ .getResourceAsStream("org/python/expose/generate/SimpleExposed.class"); ExposedTypeProcessor ice = new ExposedTypeProcessor(in); assertEquals("simpleexposed", ice.getName()); - assertEquals(18, ice.getMethodExposers().size()); + assertEquals(19, 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 2008-11-28 10:06:54 UTC (rev 5654) +++ trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java 2008-11-28 21:10:39 UTC (rev 5655) @@ -189,6 +189,10 @@ assertEquals("a", createBound("charReturn", CHAR).__call__().toString()); } + public void testNullReturns() throws Exception { + assertEquals(Py.None, createBound("stringReturnNull", STRING).__call__()); + } + public void testClassMethod() throws Exception { ClassMethodExposer exp = new ClassMethodExposer(Type.getType(SimpleExposed.class), Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, Modified: trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java 2008-11-28 10:06:54 UTC (rev 5654) +++ trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java 2008-11-28 21:10:39 UTC (rev 5655) @@ -123,6 +123,11 @@ return 'a'; } + @ExposedMethod + public String stringReturnNull() { + return null; + } + @ExposedClassMethod public static char classmethod(PyType onType) { return 'a'; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-28 10:07:02
|
Revision: 5654 http://jython.svn.sourceforge.net/jython/?rev=5654&view=rev Author: cgroves Date: 2008-11-28 10:06:54 +0000 (Fri, 28 Nov 2008) Log Message: ----------- Expose static fields through PyBeanProperty if they share a name with the property. Instance fields supercede the propery. Modified Paths: -------------- branches/newstyle-java-types/Lib/test/test_java_integration.py branches/newstyle-java-types/src/org/python/core/PyJavaType.java branches/newstyle-java-types/src/org/python/core/PyObject.java Modified: branches/newstyle-java-types/Lib/test/test_java_integration.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_java_integration.py 2008-11-28 09:13:19 UTC (rev 5653) +++ branches/newstyle-java-types/Lib/test/test_java_integration.py 2008-11-28 10:06:54 UTC (rev 5654) @@ -55,9 +55,6 @@ A() class InstantiationTest(unittest.TestCase): - def test_cant_create_abstract(self): - self.assertRaises(TypeError, Component) - def test_can_subclass_abstract(self): class A(Component): pass @@ -339,8 +336,11 @@ class ColorTest(unittest.TestCase): def test_static_fields(self): - Color.red - Color.blue + self.assertEquals(Color(255, 0, 0), Color.RED) + # The bean accessor for getRed should be active on instances, but the static field red + # should be visible on the class + self.assertEquals(255, Color.red.red) + self.assertEquals(Color(0, 0, 255), Color.blue) def test_is_operator(self): red = Color.red @@ -363,7 +363,7 @@ y = BigDecimalTest().asBigDecimal() self.assertEqual(type(x), type(y), "BigDecimal coerced") - self.assertEqual(x, y, "BigDecimal coerced") + self.assertEqual(x, y, "coerced BigDecimal not equal to directly created version") class MethodInvTest(unittest.TestCase): Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-28 09:13:19 UTC (rev 5653) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-28 10:06:54 UTC (rev 5654) @@ -100,12 +100,13 @@ } } for (String propname : propnames.keySet()) { - if(propname.equals("")) { + if (propname.equals("")) { continue; } String npropname = normalize_name(StringUtil.decapitalize(propname)); PyObject prev = dict.__finditem__(npropname); - if (prev != null && prev instanceof PyReflectedFunction) { + if (prev != null && (!(prev instanceof PyReflectedField) || + !Modifier.isStatic(((PyReflectedField)prev).field.getModifiers()))) { continue; } Method getter = null; @@ -125,7 +126,11 @@ } } if (setter != null || getter != null) { - dict.__setitem__(npropname, new PyBeanProperty(npropname, proptype, getter, setter)); + PyBeanProperty prop = new PyBeanProperty(npropname, proptype, getter, setter); + if (prev != null) { + prop.field = ((PyReflectedField)prev).field; + } + dict.__setitem__(npropname, prop); } else { // XXX error } Modified: branches/newstyle-java-types/src/org/python/core/PyObject.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-28 09:13:19 UTC (rev 5653) +++ branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-28 10:06:54 UTC (rev 5654) @@ -267,7 +267,7 @@ return Py.NoConversion; } - protected static final Map<Class<?>, Class<?>> primitiveMap = Generic.map(); + private static final Map<Class<?>, Class<?>> primitiveMap = Generic.map(); static { primitiveMap.put(Character.TYPE, Character.class); primitiveMap.put(Boolean.TYPE, Boolean.class); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-28 09:13:21
|
Revision: 5653 http://jython.svn.sourceforge.net/jython/?rev=5653&view=rev Author: cgroves Date: 2008-11-28 09:13:19 +0000 (Fri, 28 Nov 2008) Log Message: ----------- PyObject needs to handle primitive conversion in the new world Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/PyInstance.java branches/newstyle-java-types/src/org/python/core/PyObject.java Modified: branches/newstyle-java-types/src/org/python/core/PyInstance.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyInstance.java 2008-11-28 08:59:49 UTC (rev 5652) +++ branches/newstyle-java-types/src/org/python/core/PyInstance.java 2008-11-28 09:13:19 UTC (rev 5653) @@ -82,23 +82,6 @@ if (c.isInstance(this)) return this; - if (c.isPrimitive()) { - if (primitiveMap == null) { - primitiveMap = new Hashtable(); - primitiveMap.put(Character.TYPE, Character.class); - primitiveMap.put(Boolean.TYPE, Boolean.class); - primitiveMap.put(Byte.TYPE, Byte.class); - primitiveMap.put(Short.TYPE, Short.class); - primitiveMap.put(Integer.TYPE, Integer.class); - primitiveMap.put(Long.TYPE, Long.class); - primitiveMap.put(Float.TYPE, Float.class); - primitiveMap.put(Double.TYPE, Double.class); - } - Class tmp = (Class)primitiveMap.get(c); - if (tmp != null) - c = tmp; - } - if (instclass.__tojava__ != null) { // try { PyObject ret = instclass.__tojava__.__call__(this, PyType.fromClass(c)); Modified: branches/newstyle-java-types/src/org/python/core/PyObject.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-28 08:59:49 UTC (rev 5652) +++ branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-28 09:13:19 UTC (rev 5653) @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.NoSuchElementException; import org.python.expose.ExposedDelete; @@ -15,6 +16,7 @@ import org.python.expose.ExposedNew; import org.python.expose.ExposedSet; import org.python.expose.ExposedType; +import org.python.util.Generic; /** * All objects known to the Jython runtime system are represented by an instance @@ -253,12 +255,30 @@ if (c.isInstance(this)) { return this; } + if (c.isPrimitive()) { + Class<?> tmp = primitiveMap.get(c); + if (tmp != null) { + c = tmp; + } + } if (c.isInstance(javaProxy)) { return javaProxy; } return Py.NoConversion; } + protected static final Map<Class<?>, Class<?>> primitiveMap = Generic.map(); + static { + primitiveMap.put(Character.TYPE, Character.class); + primitiveMap.put(Boolean.TYPE, Boolean.class); + primitiveMap.put(Byte.TYPE, Byte.class); + primitiveMap.put(Short.TYPE, Short.class); + primitiveMap.put(Integer.TYPE, Integer.class); + primitiveMap.put(Long.TYPE, Long.class); + primitiveMap.put(Float.TYPE, Float.class); + primitiveMap.put(Double.TYPE, Double.class); + } + /** * The basic method to override when implementing a callable object. * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-28 08:59:50
|
Revision: 5652 http://jython.svn.sourceforge.net/jython/?rev=5652&view=rev Author: cgroves Date: 2008-11-28 08:59:49 +0000 (Fri, 28 Nov 2008) Log Message: ----------- Whoops, didn't mean to remove Finn's copyright Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/CollectionIter.java Modified: branches/newstyle-java-types/src/org/python/core/CollectionIter.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/CollectionIter.java 2008-11-28 08:56:38 UTC (rev 5651) +++ branches/newstyle-java-types/src/org/python/core/CollectionIter.java 2008-11-28 08:59:49 UTC (rev 5652) @@ -1,3 +1,4 @@ +// Copyright (c) Finn Bock package org.python.core; import java.util.Enumeration; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-28 08:56:41
|
Revision: 5651 http://jython.svn.sourceforge.net/jython/?rev=5651&view=rev Author: cgroves Date: 2008-11-28 08:56:38 +0000 (Fri, 28 Nov 2008) Log Message: ----------- Add an EQ_PROXY to PyJavaType to pass equals through to wrapped Java instances like PyJavaInstance did. Make PyBuiltinMethod Cloneable and use clone to implement a default bind implementation. This eliminates 75% of the crud that came with creating a builtin method in Java. Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/CollectionIter.java branches/newstyle-java-types/src/org/python/core/PyBuiltinMethod.java branches/newstyle-java-types/src/org/python/core/PyJavaType.java Modified: branches/newstyle-java-types/src/org/python/core/CollectionIter.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/CollectionIter.java 2008-11-28 08:12:30 UTC (rev 5650) +++ branches/newstyle-java-types/src/org/python/core/CollectionIter.java 2008-11-28 08:56:38 UTC (rev 5651) @@ -1,59 +1,30 @@ -// Copyright (c) Finn Bock - package org.python.core; -import java.util.Dictionary; import java.util.Enumeration; import java.util.Iterator; -import java.util.Map; -class CollectionIter{ - PyObject findCollection(Object object) { - if (object instanceof Map) { - return new IteratorIter(((Map) object).keySet().iterator()); - } - if (object instanceof Iterable) { - return new IteratorIter(((Iterable)object).iterator()); - } - if (object instanceof Iterator) { - return new IteratorIter(((Iterator) object)); - } - if (object instanceof Enumeration) { - return new EnumerationIter(((Enumeration) object)); - } - if (object instanceof Dictionary) { - return new EnumerationIter(((Dictionary) object).keys()); - } - - return null; - } - -} - class EnumerationIter extends PyIterator { - private Enumeration proxy; - public EnumerationIter(Enumeration proxy) { + private Enumeration<Object> proxy; + + public EnumerationIter(Enumeration<Object> proxy) { this.proxy = proxy; } public PyObject __iternext__() { - if (!this.proxy.hasMoreElements()) - return null; - return Py.java2py(this.proxy.nextElement()); + return proxy.hasMoreElements() ? Py.java2py(proxy.nextElement()) : null; } } class IteratorIter extends PyIterator { - private Iterator proxy; - public IteratorIter(Iterator proxy) { + private Iterator<Object> proxy; + + public IteratorIter(Iterator<Object> proxy) { this.proxy = proxy; } public PyObject __iternext__() { - if (!this.proxy.hasNext()) - return null; - return Py.java2py(this.proxy.next()); + return proxy.hasNext() ? Py.java2py(proxy.next()) : null; } } Modified: branches/newstyle-java-types/src/org/python/core/PyBuiltinMethod.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyBuiltinMethod.java 2008-11-28 08:12:30 UTC (rev 5650) +++ branches/newstyle-java-types/src/org/python/core/PyBuiltinMethod.java 2008-11-28 08:56:38 UTC (rev 5651) @@ -2,7 +2,8 @@ import org.python.expose.ExposeAsSuperclass; -public abstract class PyBuiltinMethod extends PyBuiltinCallable implements ExposeAsSuperclass { +public abstract class PyBuiltinMethod extends PyBuiltinCallable implements ExposeAsSuperclass, + Cloneable { protected PyObject self; @@ -15,15 +16,31 @@ super(info); this.self = self; } - + protected PyBuiltinMethod(String name) { this(null, new DefaultInfo(name)); } - + + @Override + public PyBuiltinCallable bind(PyObject bindTo) { + if(self == null) { + PyBuiltinMethod bindable; + try { + bindable = (PyBuiltinMethod)clone(); + } catch(CloneNotSupportedException e) { + throw new RuntimeException("Didn't expect PyBuiltinMethodto throw " + + "CloneNotSupported since it implements Cloneable", e); + } + bindable.self = bindTo; + return bindable; + } + return this; + } + public PyObject getSelf(){ return self; } - + public PyMethodDescr makeDescriptor(PyType t) { return new PyMethodDescr(t, this); } Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-28 08:12:30 UTC (rev 5650) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-28 08:56:38 UTC (rev 5651) @@ -45,15 +45,12 @@ String methname = meth.getName(); String nmethname = normalize_name(methname); PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); - boolean added = false; if (reflfunc == null) { dict.__setitem__(nmethname, new PyReflectedFunction(meth)); - added = true; } else { reflfunc.addMethod(meth); - added = true; } - if (added && !Modifier.isStatic(meth.getModifiers())) { + if (!Modifier.isStatic(meth.getModifiers())) { // check for xxxX.* int n = meth.getParameterTypes().length; if (methname.startsWith("get") && n == 0) { @@ -164,6 +161,7 @@ } } } + dict.__setitem__("__eq__", new PyMethodDescr(this, EQUALS_PROXY)); if (ClassDictInit.class.isAssignableFrom(underlying_class) && underlying_class != ClassDictInit.class) { try { @@ -222,104 +220,43 @@ return Py.JavaError(e); } - protected static class LenProxy extends PyBuiltinMethodNarrow { - public LenProxy() { - super("__len__", 0, 0); - } - - protected LenProxy(PyType type, PyObject self, Info info) { - super(type, self, info); - } - + protected static final PyBuiltinMethodNarrow LEN_PROXY = + new PyBuiltinMethodNarrow("__len__", 0, 0) { @Override - public PyBuiltinCallable bind(PyObject self) { - return new LenProxy(getType(), self, info); - } - - @Override public PyObject __call__() { return Py.newInteger(((Collection<?>)self.javaProxy).size()); } - } + }; - protected static class MapGetProxy extends PyBuiltinMethodNarrow { - public MapGetProxy() { - super("__getitem__", 1, 1); - } - - protected MapGetProxy(PyType type, PyObject self, Info info) { - super(type, self, info); - } - + protected static final PyBuiltinMethodNarrow MAP_GET_PROXY = + new PyBuiltinMethodNarrow("__getitem__", 1, 1) { @Override - public PyBuiltinCallable bind(PyObject self) { - return new MapGetProxy(getType(), self, info); - } - - @Override public PyObject __call__(PyObject key) { return Py.java2py(((Map<?, ?>)self.javaProxy).get(Py.tojava(key, Object.class))); } - } + }; - protected static class MapPutProxy extends PyBuiltinMethodNarrow { - public MapPutProxy() { - super("__setitem__", 2, 2); - } - - protected MapPutProxy(PyType type, PyObject self, Info info) { - super(type, self, info); - } - + protected static final PyBuiltinMethodNarrow MAP_PUT_PROXY = + new PyBuiltinMethodNarrow("__setitem__", 2, 2) { @Override - public PyBuiltinCallable bind(PyObject self) { - return new MapPutProxy(getType(), self, info); - } - - @Override public PyObject __call__(PyObject key, PyObject value) { return Py.java2py(((Map<Object, Object>)self.javaProxy).put(Py.tojava(key, Object.class), Py.tojava(value, Object.class))); } - } + }; - protected static class MapRemoveProxy extends PyBuiltinMethodNarrow { - - public MapRemoveProxy() { - super("__delitem__", 1, 1); - } - - protected MapRemoveProxy(PyType type, PyObject self, Info info) { - super(type, self, info); - } - + protected static final PyBuiltinMethodNarrow MAP_REMOVE_PROXY = + new PyBuiltinMethodNarrow("__delitem__", 1, 1) { @Override - public PyBuiltinCallable bind(PyObject self) { - return new MapRemoveProxy(getType(), self, info); - } - - @Override public PyObject __call__(PyObject key, PyObject value) { return Py.java2py(((Map<?, ?>)self.javaProxy).remove(Py.tojava(key, Object.class))); } - } + }; - protected static class ListGetProxy extends PyBuiltinMethodNarrow { - public ListGetProxy() { - super("__getitem__", 1, 1); - } - - protected ListGetProxy(PyType type, PyObject self, Info info) { - super(type, self, info); - } - + protected static final PyBuiltinMethodNarrow LIST_GET_PROXY = + new PyBuiltinMethodNarrow("__getitem__", 1, 1){ @Override - public PyBuiltinCallable bind(PyObject self) { - return new ListGetProxy(getType(), self, info); - } - - @Override public PyObject __call__(PyObject key) { if (key instanceof PyInteger) { return Py.java2py(((List<?>)self.javaProxy).get(((PyInteger)key).getValue())); @@ -327,23 +264,11 @@ throw Py.TypeError("only integer keys accepted"); } } - } + }; - protected static class ListSetProxy extends PyBuiltinMethodNarrow { - public ListSetProxy() { - super("__setitem__", 2, 2); - } - - protected ListSetProxy(PyType type, PyObject self, Info info) { - super(type, self, info); - } - + protected static final PyBuiltinMethodNarrow LIST_SET_PROXY = + new PyBuiltinMethodNarrow("__setitem__", 2, 2) { @Override - public PyBuiltinCallable bind(PyObject self) { - return new ListSetProxy(getType(), self, info); - } - - @Override public PyObject __call__(PyObject key, PyObject value) { if (key instanceof PyInteger) { ((List<Object>)self.javaProxy).set(((PyInteger)key).getValue(), @@ -353,23 +278,11 @@ } return Py.None; } - } + }; - protected static class ListRemoveProxy extends PyBuiltinMethodNarrow { - public ListRemoveProxy() { - super("__delitem__", 1, 1); - } - - protected ListRemoveProxy(PyType type, PyObject self, Info info) { - super(type, self, info); - } - - @Override - public PyBuiltinCallable bind(PyObject self) { - return new ListRemoveProxy(getType(), self, info); - } - - @Override + protected static final PyBuiltinMethodNarrow LIST_REMOVE_PROXY = + new PyBuiltinMethodNarrow("__delitem__", 1, 1) { + @Override public PyObject __call__(PyObject key, PyObject value) { if (key instanceof PyInteger) { return Py.java2py(((List<Object>)self.javaProxy).remove(((PyInteger)key).getValue())); @@ -377,38 +290,33 @@ throw Py.TypeError("only integer keys accepted"); } } - } + }; - public static class IterableProxy extends PyBuiltinMethodNarrow { - - public IterableProxy() { - super("__iter__", 0, 0); + public static final PyBuiltinMethodNarrow ITERABLE_PROXY = + new PyBuiltinMethodNarrow("__iter__", 0, 0) { + public PyObject __call__() { + return new IteratorIter(((Iterable)self.javaProxy).iterator()); } + }; - protected IterableProxy(PyType type, PyObject self, Info info) { - super(type, self, info); - } - + public static final PyBuiltinMethodNarrow EQUALS_PROXY = + new PyBuiltinMethodNarrow("__eq__", 1, 1) { @Override - public PyBuiltinCallable bind(PyObject self) { - return new IterableProxy(getType(), self, info); + public PyObject __call__(PyObject o) { + return self.javaProxy.equals(o.__tojava__(self.javaProxy.getClass())) ? Py.True + : Py.False; } + }; - @Override - public PyObject __call__() { - return new IteratorIter(((Iterable)self.javaProxy).iterator()); - } - } - static Map<Class<?>, PyBuiltinMethod[]> _collectionProxies = Generic.map(); static { - _collectionProxies.put(Iterable.class, new PyBuiltinMethod[] {new IterableProxy()}); - _collectionProxies.put(Collection.class, new PyBuiltinMethod[] {new LenProxy()}); - _collectionProxies.put(Map.class, new PyBuiltinMethod[] {new MapGetProxy(), - new MapPutProxy(), - new MapRemoveProxy()}); - _collectionProxies.put(List.class, new PyBuiltinMethod[] {new ListGetProxy(), - new ListSetProxy(), - new ListRemoveProxy()}); + _collectionProxies.put(Iterable.class, new PyBuiltinMethod[] {ITERABLE_PROXY}); + _collectionProxies.put(Collection.class, new PyBuiltinMethod[] {LEN_PROXY}); + _collectionProxies.put(Map.class, new PyBuiltinMethod[] {MAP_GET_PROXY, + MAP_PUT_PROXY, + MAP_REMOVE_PROXY}); + _collectionProxies.put(List.class, new PyBuiltinMethod[] {LIST_GET_PROXY, + LIST_SET_PROXY, + LIST_REMOVE_PROXY}); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-28 08:12:34
|
Revision: 5650 http://jython.svn.sourceforge.net/jython/?rev=5650&view=rev Author: cgroves Date: 2008-11-28 08:12:30 +0000 (Fri, 28 Nov 2008) Log Message: ----------- Check for abstract classes and interfaces before attempting to auto-create a proxy Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/PyObject.java Modified: branches/newstyle-java-types/src/org/python/core/PyObject.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-27 22:17:41 UTC (rev 5649) +++ branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-28 08:12:30 UTC (rev 5650) @@ -2,6 +2,7 @@ package org.python.core; import java.io.Serializable; +import java.lang.reflect.Modifier; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; @@ -109,10 +110,16 @@ * by our __init__. */ protected void proxyInit() { - if (javaProxy != null || getType().getProxyType() == null) { + Class<?> c = getType().getProxyType(); + if (javaProxy != null || c == null) { return; } - Class<?> c = getType().getProxyType(); + int mods = c.getModifiers(); + if (Modifier.isInterface(mods)) { + throw Py.TypeError("can't instantiate interface (" + c.getName() + ")"); + } else if (Modifier.isAbstract(mods)) { + throw Py.TypeError("can't instantiate abstract class (" + c.getName() + ")"); + } PyProxy proxy; ThreadState ts = Py.getThreadState(); try { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-11-27 22:17:45
|
Revision: 5649 http://jython.svn.sourceforge.net/jython/?rev=5649&view=rev Author: otmarhumbel Date: 2008-11-27 22:17:41 +0000 (Thu, 27 Nov 2008) Log Message: ----------- better approximation of the progress Modified Paths: -------------- trunk/installer/src/java/org/python/util/install/JarInstaller.java Modified: trunk/installer/src/java/org/python/util/install/JarInstaller.java =================================================================== --- trunk/installer/src/java/org/python/util/install/JarInstaller.java 2008-11-27 20:56:40 UTC (rev 5648) +++ trunk/installer/src/java/org/python/util/install/JarInstaller.java 2008-11-27 22:17:41 UTC (rev 5649) @@ -178,22 +178,22 @@ } private int approximateNumberOfEntries(InstallationType installationType) { - int numberOfEntries = 65; // core (minimum) + int numberOfEntries = 100; // core (minimum) if (installationType.installLibraryModules()) { if (installationType.isStandalone()) { - numberOfEntries += 240; + numberOfEntries += 480; } else { - numberOfEntries += 664; + numberOfEntries += 1260; } } if (installationType.installDemosAndExamples()) { - numberOfEntries += 44; + numberOfEntries += 50; } if (installationType.installDocumentation()) { - numberOfEntries += 209; + numberOfEntries += 185; } if (installationType.installSources()) { - numberOfEntries += 401; + numberOfEntries += 585; } return numberOfEntries; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-27 20:56:43
|
Revision: 5648 http://jython.svn.sourceforge.net/jython/?rev=5648&view=rev Author: pjenvey Date: 2008-11-27 20:56:40 +0000 (Thu, 27 Nov 2008) Log Message: ----------- small cleanup, match CPython's __repr__ Modified Paths: -------------- trunk/jython/src/org/python/modules/zipimport/zipimporter.java Modified: trunk/jython/src/org/python/modules/zipimport/zipimporter.java =================================================================== --- trunk/jython/src/org/python/modules/zipimport/zipimporter.java 2008-11-27 20:56:10 UTC (rev 5647) +++ trunk/jython/src/org/python/modules/zipimport/zipimporter.java 2008-11-27 20:56:40 UTC (rev 5648) @@ -50,12 +50,12 @@ "a zipfile. ZipImportError is raised if 'archivepath' doesn't point to\n" + "a valid Zip archive."); - /** zip_searchorder defines how we search for a module in the Zip + /** zipSearchOrder defines how we search for a module in the Zip * archive */ static enum EntryType { IS_SOURCE, IS_BYTECODE, IS_PACKAGE }; - static final SearchOrderEntry[] zip_searchorder = new SearchOrderEntry[] { + static final SearchOrderEntry[] zipSearchOrder = new SearchOrderEntry[] { new SearchOrderEntry(File.separator + "__init__$py.class", EnumSet.of(EntryType.IS_PACKAGE, EntryType.IS_BYTECODE)), new SearchOrderEntry(File.separator + "__init__.py", @@ -126,9 +126,7 @@ break; } - String childFile = pathFile.getPath(); - prefix = childFile.substring(childFile.lastIndexOf(File.separator) + 1) - + File.separator + prefix; + prefix = pathFile.getName() + File.separator + prefix; pathFile = parentFile; } @@ -364,8 +362,7 @@ private ModuleInfo getModuleInfo(String fullname) { String path = makeFilename(prefix, getSubname(fullname)); - for (int i = 0; i < zip_searchorder.length; i++) { - SearchOrderEntry entry = zip_searchorder[i]; + for (SearchOrderEntry entry : zipSearchOrder) { PyObject tocEntry = files.__finditem__(path + entry.suffix); if (tocEntry == null) continue; @@ -392,8 +389,7 @@ return null; } - for (int i = 0; i < zip_searchorder.length; i++) { - SearchOrderEntry entry = zip_searchorder[i]; + for (SearchOrderEntry entry : zipSearchOrder) { String suffix = entry.suffix; String searchPath = path + suffix; @@ -606,7 +602,12 @@ @ExposedMethod(names = "__repr__") final String zipimporter_toString() { - return "<zipimporter object \"" + archive + "\">"; + String displayArchive = archive != null ? archive : "???"; + if (prefix != null && !"".equals(prefix)) { + return String.format("<zipimporter object \"%.300s%c%.150s\">", + displayArchive, File.separatorChar, prefix); + } + return String.format("<zipimporter object \"%.300s\">", displayArchive); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |