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: <pj...@us...> - 2009-10-29 04:28:09
|
Revision: 6929 http://jython.svn.sourceforge.net/jython/?rev=6929&view=rev Author: pjenvey Date: 2009-10-29 04:28:03 +0000 (Thu, 29 Oct 2009) Log Message: ----------- avoid unnecessary copying when creating lists Modified Paths: -------------- trunk/jython/src/org/python/core/PyDictionary.java Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2009-10-29 04:26:36 UTC (rev 6928) +++ trunk/jython/src/org/python/core/PyDictionary.java 2009-10-29 04:28:03 UTC (rev 6929) @@ -619,7 +619,7 @@ for (Entry<PyObject, PyObject> entry : table.entrySet()) { list.add(new PyTuple(entry.getKey(), entry.getValue())); } - return new PyList(list); + return PyList.fromList(list); } /** @@ -631,12 +631,12 @@ @ExposedMethod(doc = BuiltinDocs.dict_keys_doc) final PyList dict_keys() { - return new PyList(new ArrayList<PyObject>(table.keySet())); + return PyList.fromList(new ArrayList<PyObject>(table.keySet())); } @ExposedMethod(doc = BuiltinDocs.dict_values_doc) final PyList dict_values() { - return new PyList(new ArrayList<PyObject>(table.values())); + return PyList.fromList(new ArrayList<PyObject>(table.values())); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-29 04:26:57
|
Revision: 6928 http://jython.svn.sourceforge.net/jython/?rev=6928&view=rev Author: pjenvey Date: 2009-10-29 04:26:36 +0000 (Thu, 29 Oct 2009) Log Message: ----------- cache the jython check, only apply the ReflectedFunctionType check to jython Modified Paths: -------------- trunk/jython/Lib/inspect.py Modified: trunk/jython/Lib/inspect.py =================================================================== --- trunk/jython/Lib/inspect.py 2009-10-29 02:53:00 UTC (rev 6927) +++ trunk/jython/Lib/inspect.py 2009-10-29 04:26:36 UTC (rev 6928) @@ -30,7 +30,9 @@ import sys, os, types, string, re, dis, imp, tokenize, linecache from operator import attrgetter -ReflectedFunctionType = type(os.listdir) +_jython = sys.platform.startswith('java') +if _jython: + _ReflectedFunctionType = type(os.listdir) # ----------------------------------------------------------- type-checking def ismodule(object): @@ -198,7 +200,7 @@ or isfunction(object) or ismethod(object) or ismethoddescriptor(object) - or isinstance(object, ReflectedFunctionType)) + or (_jython and isinstance(object, _ReflectedFunctionType))) def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. @@ -690,7 +692,7 @@ if not iscode(co): raise TypeError('arg is not a code object') - if not sys.platform.startswith('java'): + if not _jython: # Jython doesn't have co_code code = co.co_code This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-29 02:53:23
|
Revision: 6927 http://jython.svn.sourceforge.net/jython/?rev=6927&view=rev Author: pjenvey Date: 2009-10-29 02:53:00 +0000 (Thu, 29 Oct 2009) Log Message: ----------- dict doesn't need __nonzero__ exposed, doc setdefault Modified Paths: -------------- trunk/jython/src/org/python/core/PyDictionary.java Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2009-10-28 23:41:45 UTC (rev 6926) +++ trunk/jython/src/org/python/core/PyDictionary.java 2009-10-29 02:53:00 UTC (rev 6927) @@ -116,12 +116,6 @@ @Override public boolean __nonzero__() { - return dict___nonzero__(); - } - - //XXX: CPython's dict does not define __nonzero__ - @ExposedMethod - final boolean dict___nonzero__() { return table.size() != 0; } @@ -549,14 +543,13 @@ return dict_setdefault(key, failobj); } - //XXX: needs __doc__ but CPython does not define setdefault - @ExposedMethod(defaults = "Py.None") + @ExposedMethod(defaults = "Py.None", doc = BuiltinDocs.dict_setdefault_doc) final PyObject dict_setdefault(PyObject key, PyObject failobj) { PyObject oldValue = table.putIfAbsent(key, failobj); return oldValue == null ? failobj : oldValue; } - //XXX: needs __doc__ but CPython does not define setifabsent + // XXX: needs __doc__ but CPython does not define setifabsent @ExposedMethod(defaults = "Py.None") final PyObject dict_setifabsent(PyObject key, PyObject failobj) { PyObject oldValue = table.putIfAbsent(key, failobj); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-28 23:42:04
|
Revision: 6926 http://jython.svn.sourceforge.net/jython/?rev=6926&view=rev Author: pjenvey Date: 2009-10-28 23:41:45 +0000 (Wed, 28 Oct 2009) Log Message: ----------- coding standards Modified Paths: -------------- trunk/jython/src/org/python/core/PyDictionary.java Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2009-10-28 16:01:21 UTC (rev 6925) +++ trunk/jython/src/org/python/core/PyDictionary.java 2009-10-28 23:41:45 UTC (rev 6926) @@ -1,4 +1,7 @@ -// Copyright (c) Corporation for National Research Initiatives +/* + * Copyright (c) Corporation for National Research Initiatives + * Copyright (c) Jython Developers + */ package org.python.core; import java.util.AbstractSet; @@ -73,8 +76,8 @@ */ public PyDictionary(PyObject elements[]) { this(); - for (int i = 0; i < elements.length; i+=2) { - table.put(elements[i], elements[i+1]); + for (int i = 0; i < elements.length; i += 2) { + table.put(elements[i], elements[i + 1]); } } @@ -101,6 +104,7 @@ return d; } + @Override public int __len__() { return dict___len__(); } @@ -110,6 +114,7 @@ return table.size(); } + @Override public boolean __nonzero__() { return dict___nonzero__(); } @@ -120,10 +125,12 @@ return table.size() != 0; } + @Override public PyObject __finditem__(int index) { throw Py.TypeError("loop over non-sequence"); } + @Override public PyObject __finditem__(PyObject key) { return table.get(key); } @@ -146,8 +153,9 @@ throw Py.KeyError(key); } + @Override public void __setitem__(PyObject key, PyObject value) { - dict___setitem__(key,value); + dict___setitem__(key, value); } @ExposedMethod(doc = BuiltinDocs.dict___setitem___doc) @@ -155,6 +163,7 @@ table.put(key, value); } + @Override public void __delitem__(PyObject key) { dict___delitem__(key); } @@ -162,10 +171,12 @@ @ExposedMethod(doc = BuiltinDocs.dict___delitem___doc) final void dict___delitem__(PyObject key) { Object ret = table.remove(key); - if (ret == null) + if (ret == null) { throw Py.KeyError(key.toString()); + } } + @Override public PyObject __iter__() { return dict___iter__(); } @@ -175,6 +186,7 @@ return iterkeys(); } + @Override public String toString() { return dict_toString(); } @@ -187,14 +199,13 @@ } StringBuilder buf = new StringBuilder("{"); - for (Entry<PyObject, PyObject> entry : table.entrySet()) { buf.append((entry.getKey()).__repr__().toString()); buf.append(": "); buf.append((entry.getValue()).__repr__().toString()); buf.append(", "); } - if(buf.length() > 1){ + if (buf.length() > 1) { buf.delete(buf.length() - 2, buf.length()); } buf.append("}"); @@ -203,101 +214,113 @@ return buf.toString(); } - public PyObject __eq__(PyObject ob_other) { - return dict___eq__(ob_other); + @Override + public PyObject __eq__(PyObject otherObj) { + return dict___eq__(otherObj); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.dict___eq___doc) - final PyObject dict___eq__(PyObject ob_other) { + final PyObject dict___eq__(PyObject otherObj) { PyType thisType = getType(); - PyType otherType = ob_other.getType(); + PyType otherType = otherObj.getType(); if (otherType != thisType && !thisType.isSubType(otherType) && !otherType.isSubType(thisType)) { return null; } - PyDictionary other = (PyDictionary)ob_other; + PyDictionary other = (PyDictionary)otherObj; int an = table.size(); int bn = other.table.size(); - if (an != bn) + if (an != bn) { return Py.False; + } PyList akeys = keys(); - for (int i=0; i<an; i++) { + for (int i = 0; i < an; i++) { PyObject akey = akeys.pyget(i); PyObject bvalue = other.__finditem__(akey); - if (bvalue == null) + if (bvalue == null) { return Py.False; + } PyObject avalue = __finditem__(akey); - if (!avalue._eq(bvalue).__nonzero__()) + if (!avalue._eq(bvalue).__nonzero__()) { return Py.False; + } } return Py.True; } - public PyObject __ne__(PyObject ob_other) { - return dict___ne__(ob_other); + @Override + public PyObject __ne__(PyObject otherObj) { + return dict___ne__(otherObj); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.dict___ne___doc) - final PyObject dict___ne__(PyObject ob_other) { - PyObject eq_result = __eq__(ob_other); - if (eq_result == null) return null; + final PyObject dict___ne__(PyObject otherObj) { + PyObject eq_result = __eq__(otherObj); + if (eq_result == null) { + return null; + } return eq_result.__not__(); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.dict___lt___doc) - final PyObject dict___lt__(PyObject ob_other){ - int result = __cmp__(ob_other); - if(result == -2){ + final PyObject dict___lt__(PyObject otherObj) { + int result = __cmp__(otherObj); + if (result == -2) { return null; } return result < 0 ? Py.True : Py.False; } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.dict___gt___doc) - final PyObject dict___gt__(PyObject ob_other){ - int result = __cmp__(ob_other); - if(result == -2){ + final PyObject dict___gt__(PyObject otherObj) { + int result = __cmp__(otherObj); + if (result == -2) { return null; } return result > 0 ? Py.True : Py.False; } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.dict___le___doc) - final PyObject dict___le__(PyObject ob_other){ - int result = __cmp__(ob_other); - if(result == -2){ + final PyObject dict___le__(PyObject otherObj) { + int result = __cmp__(otherObj); + if (result == -2) { return null; } return result <= 0 ? Py.True : Py.False; } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.dict___ge___doc) - final PyObject dict___ge__(PyObject ob_other){ - int result = __cmp__(ob_other); - if(result == -2){ + final PyObject dict___ge__(PyObject otherObj) { + int result = __cmp__(otherObj); + if (result == -2) { return null; } return result >= 0 ? Py.True : Py.False; } - public int __cmp__(PyObject ob_other) { - return dict___cmp__(ob_other); + @Override + public int __cmp__(PyObject otherObj) { + return dict___cmp__(otherObj); } @ExposedMethod(type = MethodType.CMP, doc = BuiltinDocs.dict___cmp___doc) - final int dict___cmp__(PyObject ob_other) { + final int dict___cmp__(PyObject otherObj) { PyType thisType = getType(); - PyType otherType = ob_other.getType(); + PyType otherType = otherObj.getType(); if (otherType != thisType && !thisType.isSubType(otherType) && !otherType.isSubType(thisType)) { return -2; } - PyDictionary other = (PyDictionary)ob_other; + PyDictionary other = (PyDictionary)otherObj; int an = table.size(); int bn = other.table.size(); - if (an < bn) return -1; - if (an > bn) return 1; + if (an < bn) { + return -1; + } + if (an > bn) { + return 1; + } PyList akeys = keys(); PyList bkeys = other.keys(); @@ -305,26 +328,28 @@ akeys.sort(); bkeys.sort(); - for (int i=0; i<bn; i++) { + for (int i = 0; i < bn; i++) { PyObject akey = akeys.pyget(i); PyObject bkey = bkeys.pyget(i); int c = akey._cmp(bkey); - if (c != 0) + if (c != 0) { return c; + } PyObject avalue = __finditem__(akey); PyObject bvalue = other.__finditem__(bkey); - if(avalue == null){ - if(bvalue == null){ + if (avalue == null) { + if (bvalue == null) { continue; } return -3; - }else if(bvalue == null){ + } else if (bvalue == null) { return -3; } c = avalue._cmp(bvalue); - if (c != 0) + if (c != 0) { return c; + } } return 0; } @@ -341,6 +366,7 @@ return table.containsKey(key); } + @Override public boolean __contains__(PyObject o) { return dict___contains__(o); } @@ -351,24 +377,20 @@ } /** - * Return this[key] if the key exists in the mapping, default_object - * is returned otherwise. + * Return this[key] if the key exists in the mapping, defaultObj is returned + * otherwise. * - * @param key the key to lookup in the dictionary. - * @param default_object the value to return if the key does not - * exists in the mapping. + * @param key the key to lookup in the dictionary. + * @param defaultObj the value to return if the key does not exists in the mapping. */ - public PyObject get(PyObject key, PyObject default_object) { - return dict_get(key,default_object); + public PyObject get(PyObject key, PyObject defaultObj) { + return dict_get(key, defaultObj); } @ExposedMethod(defaults = "Py.None", doc = BuiltinDocs.dict_get_doc) - final PyObject dict_get(PyObject key, PyObject default_object) { + final PyObject dict_get(PyObject key, PyObject defaultObj) { PyObject o = table.get(key); - if (o == null) - return default_object; - else - return o; + return o == null ? defaultObj : o; } /** @@ -441,8 +463,8 @@ } } - private void merge(Map<Object,Object> other) { - for (Entry<Object,Object> entry : other.entrySet()) { + private void merge(Map<Object, Object> other) { + for (Entry<Object, Object> entry : other.entrySet()) { dict___setitem__(Py.java2py(entry.getKey()), Py.java2py(entry.getValue())); } } @@ -524,29 +546,21 @@ * if key does not already exist. */ public PyObject setdefault(PyObject key, PyObject failobj) { - return dict_setdefault(key,failobj); + return dict_setdefault(key, failobj); } //XXX: needs __doc__ but CPython does not define setdefault @ExposedMethod(defaults = "Py.None") final PyObject dict_setdefault(PyObject key, PyObject failobj) { PyObject oldValue = table.putIfAbsent(key, failobj); - if (oldValue == null) { - return failobj; - } else { - return oldValue; - } + return oldValue == null ? failobj : oldValue; } //XXX: needs __doc__ but CPython does not define setifabsent @ExposedMethod(defaults = "Py.None") final PyObject dict_setifabsent(PyObject key, PyObject failobj) { PyObject oldValue = table.putIfAbsent(key, failobj); - if (oldValue == null) { - return Py.None; - } else { - return oldValue; - } + return oldValue == null ? Py.None : oldValue; } @@ -589,8 +603,9 @@ @ExposedMethod(doc = BuiltinDocs.dict_popitem_doc) final PyObject dict_popitem() { Iterator<Entry<PyObject, PyObject>> it = table.entrySet().iterator(); - if (!it.hasNext()) + if (!it.hasNext()) { throw Py.KeyError("popitem(): dictionary is empty"); + } Entry<PyObject, PyObject> entry = it.next(); PyTuple tuple = new PyTuple(entry.getKey(), entry.getValue()); it.remove(); @@ -667,6 +682,7 @@ return new ValuesIter(table.values()); } + @Override public int hashCode() { return dict___hash__(); } @@ -697,6 +713,7 @@ size = values.size(); } + @Override public PyObject __iternext__() { if (table.size() != size) { throw Py.RuntimeError("dictionary changed size during iteration"); @@ -719,6 +736,7 @@ size = items.size(); } + @Override public PyObject __iternext__() { if (table.size() != size) { throw Py.RuntimeError("dictionary changed size during iteration"); @@ -821,7 +839,11 @@ /** Basic implementation of Entry that just holds onto a key and value and returns them. */ class SimpleEntry implements Entry { - public SimpleEntry(Object key, Object value){ + protected Object key; + + protected Object value; + + public SimpleEntry(Object key, Object value) { this.key = key; this.value = value; } @@ -834,8 +856,9 @@ return value; } + @Override public boolean equals(Object o) { - if(!(o instanceof Map.Entry)) { + if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry)o; @@ -846,10 +869,12 @@ return o1 == null ? o2 == null : o1.equals(o2); } + @Override public int hashCode() { return ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode()); } + @Override public String toString() { return key + "=" + value; } @@ -857,10 +882,6 @@ public Object setValue(Object val) { throw new UnsupportedOperationException("Not supported by this view"); } - - protected Object key; - - protected Object value; } /** @@ -877,18 +898,23 @@ super(entry.getKey(), entry.getValue()); } + @Override public boolean equals(Object o) { - if (o == null || !(o instanceof Entry)) return false; + if (o == null || !(o instanceof Entry)) { + return false; + } Entry me = new JavaToPyMapEntry((Entry)o); return o.equals(me); } // tojava is called in getKey and getValue so the raw key and value can be // used to create a new SimpleEntry in getEntry. + @Override public Object getKey() { return PyDictionary.tojava(key); } + @Override public Object getValue() { return PyDictionary.tojava(value); } @@ -923,10 +949,12 @@ super(coll); } + @Override Object toJava(Object o) { return PyDictionary.tojava(o); } + @Override Object toPython(Object o) { return Py.java2py(o); } @@ -948,9 +976,11 @@ // We know that PyMapEntrySet will only contains entries, so if the object being passed in is // null or not an Entry, then return null which will match nothing for remove and contains // methods. + @Override Object toPython(Object o) { - if(o == null || !(o instanceof Entry)) + if (o == null || !(o instanceof Entry)) { return null; + } if (o instanceof PyToJavaMapEntry) { // Use the original entry from PyDictionary return ((PyToJavaMapEntry)o).getEntry(); @@ -959,6 +989,7 @@ } } + @Override Object toJava(Object o) { return new PyToJavaMapEntry((Entry)o); } @@ -975,6 +1006,8 @@ */ abstract class PyMapSet extends AbstractSet { + private final Collection coll; + PyMapSet(Collection coll) { this.coll = coll; } @@ -983,18 +1016,22 @@ abstract Object toPython(Object obj); + @Override public int size() { return coll.size(); } + @Override public boolean contains(Object o) { return coll.contains(toPython(o)); } + @Override public boolean remove(Object o) { return coll.remove(toPython(o)); } + @Override public void clear() { coll.clear(); } @@ -1022,9 +1059,8 @@ } } + @Override public Iterator iterator() { return new PySetIter(coll.iterator()); } - - private final Collection coll; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-28 16:01:33
|
Revision: 6925 http://jython.svn.sourceforge.net/jython/?rev=6925&view=rev Author: fwierzbicki Date: 2009-10-28 16:01:21 +0000 (Wed, 28 Oct 2009) Log Message: ----------- Bringing in pypy's ast.py generator to see if I can munge it to work for Jython. Added Paths: ----------- trunk/jython/ast/asdl_py.py Added: trunk/jython/ast/asdl_py.py =================================================================== --- trunk/jython/ast/asdl_py.py (rev 0) +++ trunk/jython/ast/asdl_py.py 2009-10-28 16:01:21 UTC (rev 6925) @@ -0,0 +1,642 @@ +""" +Generate AST node definitions from an ASDL description. +""" + +import sys +import os +import asdl + + +class ASDLVisitor(asdl.VisitorBase): + + def __init__(self, stream, data): + super(ASDLVisitor, self).__init__() + self.stream = stream + self.data = data + + def visitModule(self, mod, *args): + for df in mod.dfns: + self.visit(df, *args) + + def visitSum(self, sum, *args): + for tp in sum.types: + self.visit(tp, *args) + + def visitType(self, tp, *args): + self.visit(tp.value, *args) + + def visitProduct(self, prod, *args): + for field in prod.fields: + self.visit(field, *args) + + def visitConstructor(self, cons, *args): + for field in cons.fields: + self.visit(field, *args) + + def visitField(self, field): + pass + + def emit(self, line, level=0): + indent = " "*level + self.stream.write(indent + line + "\n") + + +def is_simple_sum(sum): + assert isinstance(sum, asdl.Sum) + for constructor in sum.types: + if constructor.fields: + return False + return True + + +class ASTNodeVisitor(ASDLVisitor): + + def visitType(self, tp): + self.visit(tp.value, tp.name) + + def visitSum(self, sum, base): + if is_simple_sum(sum): + self.emit("class %s(AST):" % (base,)) + self.emit("") + self.emit("def to_simple_int(self, space):", 1) + self.emit("w_msg = space.wrap(\"not a valid %s\")" % (base,), 2) + self.emit("raise OperationError(space.w_TypeError, w_msg)", 2) + self.emit("") + for i, cons in enumerate(sum.types): + self.emit("class _%s(%s):" % (cons.name, base)) + self.emit("") + self.emit("def to_simple_int(self, space):", 1) + self.emit("return %i" % (i + 1,), 2) + self.emit("") + for i, cons in enumerate(sum.types): + self.emit("%s = %i" % (cons.name, i + 1)) + self.emit("") + self.emit("%s_to_class = [" % (base,)) + for cons in sum.types: + self.emit("_%s," % (cons.name,), 1) + self.emit("]") + self.emit("") + else: + self.emit("class %s(AST):" % (base,)) + self.emit("") + slots = ", ".join(repr(attr.name.value) for attr in sum.attributes) + self.emit("__slots__ = (%s)" % (slots,), 1) + self.emit("") + if sum.attributes: + args = ", ".join(attr.name.value for attr in sum.attributes) + self.emit("def __init__(self, %s):" % (args,), 1) + for attr in sum.attributes: + self.visit(attr) + self.emit("") + for cons in sum.types: + self.visit(cons, base, sum.attributes) + self.emit("") + + def visitProduct(self, product, name): + self.emit("class %s(AST):" % (name,)) + self.emit("") + slots = self.make_slots(product.fields) + self.emit("__slots__ = (%s)" % (slots,), 1) + self.emit("") + self.make_constructor(product.fields, product) + self.emit("") + self.emit("def walkabout(self, visitor):", 1) + self.emit("visitor.visit_%s(self)" % (name,), 2) + self.emit("") + self.make_var_syncer(product.fields, product, name) + + def make_slots(self, fields): + slots = [] + for field in fields: + name = repr(field.name.value) + slots.append(name) + if field.seq: + slots.append("'w_%s'" % (field.name,)) + return ", ".join(slots) + + def make_var_syncer(self, fields, node, name): + self.emit("def sync_app_attrs(self, space):", 1) + config = (self.data.optional_masks[node], + self.data.required_masks[node]) + self.emit("if (self.initialization_state & ~%i) ^ %i:" % config, 2) + names = [] + for field in fields: + if field.opt: + names.append("None") + else: + names.append(repr(field.name.value)) + sub = (", ".join(names), name.value) + self.emit("missing_field(space, self.initialization_state, [%s], %r)" + % sub, 3) + self.emit("else:", 2) + # Fill in all the default fields. + doing_something = False + for field in fields: + if field.opt: + doing_something = True + flag = self.data.field_masks[field] + self.emit("if not self.initialization_state & %i:" % (flag,), 3) + default = "0" if field.type.value == "int" else "None" + self.emit("self.%s = %s" % (field.name, default), 4) + if not doing_something: + self.emit("pass", 3) + for attr in fields: + if attr.seq: + self.emit("w_list = self.w_%s" % (attr.name,), 2) + self.emit("if w_list is not None:", 2) + self.emit("list_w = space.viewiterable(w_list)", 3) + self.emit("if list_w:", 3) + unwrapper = get_unwrapper(attr.type.value, "w_obj", + self.data.simple_types) + config = (attr.name, unwrapper) + self.emit("self.%s = [%s for w_obj in list_w]" % config, + 4), + self.emit("else:", 3) + self.emit("self.%s = None" % (attr.name,), 4) + if attr.type.value not in asdl.builtin_types and \ + attr.type.value not in self.data.simple_types: + self.emit("if self.%s is not None:" % (attr.name,), 2) + self.emit("for node in self.%s:" % (attr.name,), 3) + self.emit("node.sync_app_attrs(space)", 4) + elif attr.type.value not in asdl.builtin_types and \ + attr.type.value not in self.data.simple_types: + doing_something = True + level = 2 + if attr.opt: + self.emit("if self.%s:" % (attr.name,), 2) + level += 1 + self.emit("self.%s.sync_app_attrs(space)" % (attr.name,), level) + self.emit("") + + def make_constructor(self, fields, node, extras=None, base=None): + if fields or extras: + arg_fields = fields + extras if extras else fields + args = ", ".join(str(field.name) for field in arg_fields) + self.emit("def __init__(self, %s):" % args, 1) + for field in fields: + self.visit(field) + if extras: + base_args = ", ".join(str(field.name) for field in extras) + self.emit("%s.__init__(self, %s)" % (base, base_args), 2) + else: + self.emit("def __init__(self):", 1) + have_everything = self.data.required_masks[node] | \ + self.data.optional_masks[node] + self.emit("self.initialization_state = %i" % (have_everything,), 2) + + def visitConstructor(self, cons, base, extra_attributes): + self.emit("class %s(%s):" % (cons.name, base)) + self.emit("") + slots = self.make_slots(cons.fields) + self.emit("__slots__ = (%s)" % (slots,), 1) + self.emit("") + for field in self.data.cons_attributes[cons]: + subst = (field.name, self.data.field_masks[field]) + self.emit("_%s_mask = %i" % subst, 1) + self.emit("") + self.make_constructor(cons.fields, cons, extra_attributes, base) + self.emit("") + self.emit("def walkabout(self, visitor):", 1) + self.emit("visitor.visit_%s(self)" % (cons.name,), 2) + self.emit("") + self.emit("def mutate_over(self, visitor):", 1) + for field in cons.fields: + if field.type.value not in asdl.builtin_types and \ + field.type.value not in self.data.prod_simple: + if field.opt or field.seq: + level = 3 + self.emit("if self.%s:" % (field.name,), 2) + else: + level = 2 + if field.seq: + sub = (field.name,) + self.emit("visitor._mutate_sequence(self.%s)" % sub, level) + else: + sub = (field.name, field.name) + self.emit("self.%s = self.%s.mutate_over(visitor)" % sub, + level) + self.emit("return visitor.visit_%s(self)" % (cons.name,), 2) + self.emit("") + self.make_var_syncer(cons.fields + self.data.cons_attributes[cons], + cons, cons.name) + + def visitField(self, field): + self.emit("self.%s = %s" % (field.name, field.name), 2) + if field.seq: + self.emit("self.w_%s = None" % (field.name,), 2) + + +class ASTVisitorVisitor(ASDLVisitor): + """A meta visitor! :)""" + + def visitModule(self, mod): + self.emit("class ASTVisitor(object):") + self.emit("") + self.emit("def visit_sequence(self, seq):", 1) + self.emit("for node in seq:", 2) + self.emit("node.walkabout(self)", 3) + self.emit("") + self.emit("def default_visitor(self, node):", 1) + self.emit("raise NodeVisitorNotImplemented", 2) + self.emit("") + self.emit("def _mutate_sequence(self, seq):", 1) + self.emit("for i in range(len(seq)):", 2) + self.emit("seq[i] = seq[i].mutate_over(self)", 3) + self.emit("") + super(ASTVisitorVisitor, self).visitModule(mod) + self.emit("") + + def visitType(self, tp): + if not (isinstance(tp.value, asdl.Sum) and + is_simple_sum(tp.value)): + super(ASTVisitorVisitor, self).visitType(tp, tp.name) + + def visitProduct(self, prod, name): + self.emit("def visit_%s(self, node):" % (name,), 1) + self.emit("return self.default_visitor(node)", 2) + + def visitConstructor(self, cons, _): + self.emit("def visit_%s(self, node):" % (cons.name,), 1) + self.emit("return self.default_visitor(node)", 2) + + +class GenericASTVisitorVisitor(ASDLVisitor): + + def visitModule(self, mod): + self.emit("class GenericASTVisitor(ASTVisitor):") + self.emit("") + super(GenericASTVisitorVisitor, self).visitModule(mod) + self.emit("") + + def visitType(self, tp): + if not (isinstance(tp.value, asdl.Sum) and + is_simple_sum(tp.value)): + super(GenericASTVisitorVisitor, self).visitType(tp, tp.name) + + def visitProduct(self, prod, name): + self.make_visitor(name, prod.fields) + + def visitConstructor(self, cons, _): + self.make_visitor(cons.name, cons.fields) + + def make_visitor(self, name, fields): + self.emit("def visit_%s(self, node):" % (name,), 1) + have_body = False + for field in fields: + if self.visitField(field): + have_body = True + if not have_body: + self.emit("pass", 2) + self.emit("") + + def visitField(self, field): + if field.type.value not in asdl.builtin_types and \ + field.type.value not in self.data.simple_types: + if field.seq or field.opt: + self.emit("if node.%s:" % (field.name,), 2) + level = 3 + else: + level = 2 + if field.seq: + template = "self.visit_sequence(node.%s)" + else: + template = "node.%s.walkabout(self)" + self.emit(template % (field.name,), level) + return True + return False + + +asdl_type_map = { + "int" : "int_w", + "identifier" : "str_w", + "bool" : "bool_w" +} + +def get_unwrapper(tp, name, simple_types): + if tp in asdl.builtin_types: + return "space.%s(%s)" % (asdl_type_map[tp], name) + elif tp in simple_types: + return "space.interp_w(%s, %s).to_simple_int(space)" % (tp, name) + else: + return "space.interp_w(%s, %s)" % (tp, name) + + +# CPython lets blank AST nodes (no constructor arguments) be created +# and the attributes added later. In CPython, it is implemented by +# implementing applevel and c level AST as different structures and +# copying between them. This is hideous, so we use a slightly less +# ugly hack in PyPy. Each field has a bitmask which is set on the +# initialization_state attribute when the field type is set. When +# sync_app_attrs() is called, it's a simple matter of removing the +# optional field flags from initialization_state, and using XOR to +# test if all the required fields have been set. +class AppExposeVisitor(ASDLVisitor): + + def visitType(self, tp): + super(AppExposeVisitor, self).visitType(tp, tp.name) + + def visitSum(self, sum, name): + for field in sum.attributes: + self.make_property(field, name, True) + self.make_typedef(name, "AST", sum.attributes, + fields_name="_attributes") + if not is_simple_sum(sum): + super(AppExposeVisitor, self).visitSum(sum, name) + else: + for cons in sum.types: + self.make_typedef("_" + cons.name.value, name, (), cons.name, + concrete=True) + + def make_typedef(self, name, base, fields, display_name=None, + fields_name="_fields", concrete=False, needs_init=False): + if display_name is None: + display_name = name + self.emit("%s.typedef = typedef.TypeDef(\"%s\"," % (name, display_name)) + self.emit("%s.typedef," % (base,), 1) + comma_fields = ", ".join(repr(field.name.value) for field in fields) + self.emit("%s=_FieldsWrapper([%s])," % (fields_name, comma_fields), 1) + for field in fields: + getter = "%s_get_%s" % (name, field.name) + setter = "%s_set_%s" % (name, field.name) + config = (field.name, getter, setter, name) + self.emit("%s=typedef.GetSetProperty(%s, %s, cls=%s)," % config, 1) + # CPython lets you create instances of "abstract" AST nodes + # like ast.expr or even ast.AST. This doesn't seem to useful + # and would be a pain to implement safely, so we don't allow + # it. + if concrete: + self.emit("__new__=interp2app(get_AST_new(%s))," % (name,), 1) + if needs_init: + self.emit("__init__=interp2app(%s_init)," % (name,), 1) + self.emit(")") + self.emit("%s.typedef.acceptable_as_base_class = False" % (name,)) + self.emit("") + + def make_init(self, name, fields): + comma_fields = ", ".join(repr(field.name.value) for field in fields) + config = (name, comma_fields) + self.emit("_%s_field_unroller = unrolling_iterable([%s])" % config) + self.emit("def %s_init(space, w_self, args):" % (name,)) + self.emit("w_self = space.descr_self_interp_w(%s, w_self)" % (name,), 1) + for field in fields: + if field.seq: + self.emit("w_self.w_%s = None" % (field.name,), 1) + self.emit("args_w, kwargs_w = args.unpack()", 1) + self.emit("if args_w:", 1) + arity = len(fields) + if arity: + self.emit("if len(args_w) != %i:" % (arity,), 2) + self.emit("w_err = space.wrap(\"%s constructor takes 0 or %i " \ + "positional arguments\")" % (name, arity), 3) + self.emit("raise OperationError(space.w_TypeError, w_err)", 3) + self.emit("i = 0", 2) + self.emit("for field in _%s_field_unroller:" % (name,), 2) + self.emit("space.setattr(w_self, space.wrap(field), args_w[i])", 3) + self.emit("i += 1", 3) + else: + self.emit("w_err = space.wrap(\"%s constructor takes no " \ + " arguments\")" % (name,), 2) + self.emit("raise OperationError(space.w_TypeError, w_err)", 2) + self.emit("for field, w_value in kwargs_w.iteritems():", 1) + self.emit("space.setattr(w_self, space.wrap(field), w_value)", 2) + self.emit("%s_init.unwrap_spec = [ObjSpace, W_Root, Arguments]" + % (name,)) + self.emit("") + + def visitConstructor(self, cons, base): + super(AppExposeVisitor, self).visitConstructor(cons, cons.name) + self.make_init(cons.name, cons.fields + self.data.cons_attributes[cons]) + self.make_typedef(cons.name, base, cons.fields, concrete=True, + needs_init=True) + + def visitProduct(self, product, name): + super(AppExposeVisitor, self).visitProduct(product, name) + self.make_init(name, product.fields) + self.make_typedef(name, "AST", product.fields, concrete=True, + needs_init=True) + + def visitField(self, field, name): + self.make_property(field, name) + + def make_property(self, field, name, different_masks=False): + func = "def %s_get_%s(space, w_self):" % (name, field.name) + self.emit(func) + if different_masks: + flag = "w_self._%s_mask" % (field.name,) + else: + flag = self.data.field_masks[field] + self.emit("if not w_self.initialization_state & %s:" % (flag,), 1) + self.emit("w_err = space.wrap(\"attribute '%s' has not been set\")" % + (field.name,), 2) + self.emit("raise OperationError(space.w_AttributeError, w_err)", 2) + if field.seq: + self.emit("if w_self.w_%s is None:" % (field.name,), 1) + self.emit("if w_self.%s is None:" % (field.name,), 2) + self.emit("w_list = space.newlist([])", 3) + self.emit("else:", 2) + if field.type.value in self.data.simple_types: + wrapper = "%s_to_class[node - 1]()" % (field.type,) + else: + wrapper = "space.wrap(node)" + self.emit("list_w = [%s for node in w_self.%s]" % + (wrapper, field.name), 3) + self.emit("w_list = space.newlist(list_w)", 3) + self.emit("w_self.w_%s = w_list" % (field.name,), 2) + self.emit("return w_self.w_%s" % (field.name,), 1) + elif field.type.value in self.data.simple_types: + config = (field.type, field.name) + self.emit("return %s_to_class[w_self.%s - 1]()" % config, 1) + elif field.type.value in ("object", "string"): + self.emit("return w_self.%s" % (field.name,), 1) + else: + self.emit("return space.wrap(w_self.%s)" % (field.name,), 1) + self.emit("") + + func = "def %s_set_%s(space, w_self, w_new_value):" % (name, field.name) + self.emit(func) + if field.seq: + self.emit("w_self.w_%s = w_new_value" % (field.name,), 1) + elif field.type.value not in asdl.builtin_types: + # These are always other AST nodes. + if field.type.value in self.data.simple_types: + self.emit("obj = space.interp_w(%s, w_new_value)" % \ + (field.type,), 1) + self.emit("w_self.%s = obj.to_simple_int(space)" % + (field.name,), 1) + else: + config = (field.name, field.type, repr(field.opt)) + self.emit("w_self.%s = space.interp_w(%s, w_new_value, %s)" % + config, 1) + else: + level = 1 + if field.opt and field.type.value != "int": + self.emit("if space.is_w(w_new_value, space.w_None):", 1) + self.emit("w_self.%s = None" % (field.name,), 2) + level += 1 + self.emit("else:", 1) + if field.type.value == "object": + self.emit("w_self.%s = w_new_value" % (field.name,), level) + elif field.type.value == "string": + self.emit("if not space.is_true(space.isinstance(" \ + "w_new_value, space.w_basestring)):", level) + line = "w_err = space.wrap(\"some kind of string required\")" + self.emit(line, level + 1) + self.emit("raise OperationError(space.w_TypeError, w_err)", + level + 1) + self.emit("w_self.%s = w_new_value" % (field.name,), level) + else: + space_method = asdl_type_map[field.type.value] + config = (field.name, space_method) + self.emit("w_self.%s = space.%s(w_new_value)" % config, level) + self.emit("w_self.initialization_state |= %s" % (flag,), 1) + self.emit("") + + +def copy_field(field): + return asdl.Field(field.type, field.name, field.seq, field.opt) + + +class ASDLData(object): + + def __init__(self, tree): + simple_types = set() + prod_simple = set() + field_masks = {} + required_masks = {} + optional_masks = {} + cons_attributes = {} + def add_masks(fields, node): + required_mask = 0 + optional_mask = 0 + for i, field in enumerate(fields): + flag = 1 << i + field_masks[field] = flag + if field.opt: + optional_mask |= flag + else: + required_mask |= flag + required_masks[node] = required_mask + optional_masks[node] = optional_mask + for tp in tree.dfns: + if isinstance(tp.value, asdl.Sum): + sum = tp.value + if is_simple_sum(sum): + simple_types.add(tp.name.value) + else: + for cons in sum.types: + attrs = [copy_field(field) for field in sum.attributes] + add_masks(cons.fields + attrs, cons) + cons_attributes[cons] = attrs + else: + prod = tp.value + prod_simple.add(tp.name.value) + add_masks(prod.fields, prod) + prod_simple.update(simple_types) + self.cons_attributes = cons_attributes + self.simple_types = simple_types + self.prod_simple = prod_simple + self.field_masks = field_masks + self.required_masks = required_masks + self.optional_masks = optional_masks + + +HEAD = """# Generated by tools/asdl_py.py +from pypy.interpreter.baseobjspace import Wrappable, ObjSpace, W_Root +from pypy.interpreter import typedef +from pypy.interpreter.gateway import interp2app +from pypy.interpreter.argument import Arguments +from pypy.interpreter.error import OperationError +from pypy.rlib.unroll import unrolling_iterable +from pypy.tool.pairtype import extendabletype +from pypy.tool.sourcetools import func_with_new_name + + +class AST(Wrappable): + + __slots__ = ("initialization_state",) + + __metaclass__ = extendabletype + + def walkabout(self, visitor): + raise AssertionError("walkabout() implementation not provided") + + def mutate_over(self, visitor): + raise AssertionError("mutate_over() implementation not provided") + + def sync_app_attrs(self, space): + raise NotImplementedError + + +class NodeVisitorNotImplemented(Exception): + pass + + +class _FieldsWrapper(Wrappable): + "Hack around the fact we can't store tuples on a TypeDef." + + def __init__(self, fields): + self.fields = fields + + def __spacebind__(self, space): + return space.newtuple([space.wrap(field) for field in self.fields]) + + +def get_AST_new(node_class): + def generic_AST_new(space, w_type, __args__): + node = space.allocate_instance(node_class, w_type) + node.initialization_state = 0 + return space.wrap(node) + generic_AST_new.unwrap_spec = [ObjSpace, W_Root, Arguments] + return func_with_new_name(generic_AST_new, "new_%s" % node_class.__name__) + + +AST.typedef = typedef.TypeDef("AST", + _fields=_FieldsWrapper([]), + _attributes=_FieldsWrapper([]), +) +AST.typedef.acceptable_as_base_class = False + + +def missing_field(space, state, required, host): + "Find which required field is missing." + for i in range(len(required)): + if not (state >> i) & 1: + missing = required[i] + if missing is not None: + err = "required attribute '%s' missing from %s" + err = err % (missing, host) + w_err = space.wrap(err) + raise OperationError(space.w_TypeError, w_err) + raise AssertionError("should not reach here") + + +""" + +visitors = [ASTNodeVisitor, ASTVisitorVisitor, GenericASTVisitorVisitor, + AppExposeVisitor] + + +def main(argv): + if len(argv) == 3: + def_file, out_file = argv[1:] + elif len(argv) == 1: + print "Assuming default values of Python.asdl and ast.py" + here = os.path.dirname(__file__) + def_file = os.path.join(here, "Python.asdl") + out_file = os.path.join(here, "..", "ast.py") + else: + print >> sys.stderr, "invalid arguments" + return 2 + mod = asdl.parse(def_file) + data = ASDLData(mod) + fp = open(out_file, "w") + try: + fp.write(HEAD) + for visitor in visitors: + visitor(fp, data).visit(mod) + finally: + fp.close() + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) Property changes on: trunk/jython/ast/asdl_py.py ___________________________________________________________________ Added: svn:keywords + Id Added: svn:eol-style + native This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-28 06:52:41
|
Revision: 6924 http://jython.svn.sourceforge.net/jython/?rev=6924&view=rev Author: pjenvey Date: 2009-10-28 06:52:33 +0000 (Wed, 28 Oct 2009) Log Message: ----------- o further cleanup delattr/setattr handling of names o replace PyMapping_check with isMappingType o PyObject.__len__ can now safely throw TypeErrors instead of AttributeErrors, for the benefit of builtin len Modified Paths: -------------- trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PySlice.java trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2009-10-28 03:04:56 UTC (rev 6923) +++ trunk/jython/src/org/python/core/PyObject.java 2009-10-28 06:52:33 UTC (rev 6924) @@ -561,7 +561,8 @@ * @return the length of the object **/ public int __len__() { - throw Py.AttributeError("__len__"); + throw Py.TypeError(String.format("object of type '%.200s' has no len()", + getType().fastGetName())); } /** Modified: trunk/jython/src/org/python/core/PySlice.java =================================================================== --- trunk/jython/src/org/python/core/PySlice.java 2009-10-28 03:04:56 UTC (rev 6923) +++ trunk/jython/src/org/python/core/PySlice.java 2009-10-28 06:52:33 UTC (rev 6924) @@ -192,7 +192,7 @@ istop += len; } } catch (PyException pye) { - if (!pye.match(Py.AttributeError)) { + if (!pye.match(Py.TypeError)) { throw pye; } } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2009-10-28 03:04:56 UTC (rev 6923) +++ trunk/jython/src/org/python/core/__builtin__.java 2009-10-28 06:52:33 UTC (rev 6924) @@ -86,11 +86,7 @@ case 18: return __builtin__.eval(arg1); case 19: - try { - __builtin__.execfile(arg1.asString(0)); - } catch (ConversionException e) { - throw Py.TypeError("execfile's first argument must be str"); - } + __builtin__.execfile(arg1.asString()); return Py.None; case 23: return __builtin__.hex(arg1); @@ -149,19 +145,14 @@ case 13: return __builtin__.coerce(arg1, arg2); case 15: - __builtin__.delattr(arg1, asString(arg2, - "delattr(): attribute name must be string")); + __builtin__.delattr(arg1, arg2); return Py.None; case 17: return __builtin__.divmod(arg1, arg2); case 18: return __builtin__.eval(arg1, arg2); case 19: - try { - __builtin__.execfile(arg1.asString(0), arg2); - } catch (ConversionException e) { - throw Py.TypeError("execfile's first argument must be str"); - } + __builtin__.execfile(arg1.asString(), arg2); return Py.None; case 20: return __builtin__.filter(arg1, arg2); @@ -202,9 +193,6 @@ d.update(arg3); arg3 = d; } - // this catches both casts of arg3 to a PyDictionary, and - // all casts of keys in the dictionary to PyStrings inside - // apply(PyObject, PyObject, PyDictionary) PyDictionary d = (PyDictionary) arg3; return __builtin__.apply(arg1, arg2, d); } catch (ClassCastException e) { @@ -214,8 +202,7 @@ case 18: return __builtin__.eval(arg1, arg2, arg3); case 19: - __builtin__.execfile(asString(arg1, "execfile's first argument must be str", - false), arg2, arg3); + __builtin__.execfile(arg1.asString(), arg2, arg3); return Py.None; case 21: return __builtin__.getattr(arg1, arg2, arg3); @@ -224,9 +211,7 @@ case 35: return __builtin__.reduce(arg1, arg2, arg3); case 39: - __builtin__.setattr(arg1, asString(arg2, - "setattr(): attribute name must be string"), - arg3); + __builtin__.setattr(arg1, arg2, arg3); return Py.None; case 44: return fancyCall(new PyObject[] {arg1, arg2, arg3}); @@ -243,28 +228,6 @@ } } - /** - * @return arg as an interned String, or throws TypeError with mesage if asString - * throws a ConversionException - */ - private String asString(PyObject arg, String message) { - return asString(arg, message, true); - } - - /** - * @param intern - should the resulting string be interned - * @return arg as a String, or throws TypeError with message if asString throws a - * ConversionException. - */ - private String asString(PyObject arg, String message, boolean intern) { - - try { - return intern ? arg.asString(0).intern() : arg.asString(0); - } catch (ConversionException e) { - throw Py.TypeError(message); - } - } - @Override public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4) { switch (this.index) { @@ -465,8 +428,8 @@ throw Py.TypeError("number coercion failed"); } - public static void delattr(PyObject o, String n) { - o.__delattr__(n); + public static void delattr(PyObject obj, PyObject name) { + obj.__delattr__(asName(name, "delattr")); } public static PyObject dir(PyObject o) { @@ -493,25 +456,21 @@ return x._divmod(y); } - private static boolean PyMapping_check(PyObject o, boolean rw) { - return o == null || - o == Py.None || - (o instanceof PyDictionary) || - (o.__findattr__("__getitem__") != null && - (!rw || o.__findattr__("__setitem__") != null)); + private static boolean isMappingType(PyObject o) { + return o == null || o == Py.None || o.isMappingType(); } - private static void verify_mappings(PyObject globals, PyObject locals, boolean rw) { - if (!PyMapping_check(globals, rw)) { + private static void verify_mappings(PyObject globals, PyObject locals) { + if (!isMappingType(globals)) { throw Py.TypeError("globals must be a mapping"); } - if (!PyMapping_check(locals, rw)) { + if (!isMappingType(locals)) { throw Py.TypeError("locals must be a mapping"); } } public static PyObject eval(PyObject o, PyObject globals, PyObject locals) { - verify_mappings(globals, locals, false); + verify_mappings(globals, locals); PyCode code; if (o instanceof PyCode) { code = (PyCode) o; @@ -542,7 +501,7 @@ public static void execfile_flags(String name, PyObject globals, PyObject locals, CompilerFlags cflags) { - verify_mappings(globals, locals, true); + verify_mappings(globals, locals); FileInputStream file; try { file = new FileInputStream(new RelativeFile(name)); @@ -652,17 +611,9 @@ return getattr(obj, name, null); } - public static PyObject getattr(PyObject obj, PyObject name, PyObject def) { - String nameStr; - if (name instanceof PyUnicode) { - nameStr = ((PyUnicode)name).encode().intern(); - } else if (name instanceof PyString) { - nameStr = ((PyString)name).internedString(); - } else { - throw Py.TypeError("getattr(): attribute name must be string"); - } - - PyObject result = obj.__findattr__(nameStr); + public static PyObject getattr(PyObject obj, PyObject nameObj, PyObject def) { + String name = asName(nameObj, "getattr"); + PyObject result = obj.__findattr__(name); if (result != null) { return result; } @@ -670,7 +621,7 @@ return def; } // throws AttributeError - obj.noAttributeError(nameStr); + obj.noAttributeError(name); return null; } @@ -678,18 +629,10 @@ return Py.getFrame().f_globals; } - public static boolean hasattr(PyObject obj, PyObject name) { - String nameStr; - if (name instanceof PyUnicode) { - nameStr = ((PyUnicode)name).encode().intern(); - } else if (name instanceof PyString) { - nameStr = ((PyString)name).internedString(); - } else { - throw Py.TypeError("hasattr(): attribute name must be string"); - } - + public static boolean hasattr(PyObject obj, PyObject nameObj) { + String name = asName(nameObj, "hasattr"); try { - return obj.__findattr__(nameStr) != null; + return obj.__findattr__(name) != null; } catch (PyException pye) { // swallow } @@ -753,24 +696,8 @@ return new PyCallIter(callable, sentinel); } - public static int len(PyObject o) { - try { - return o.__len__(); - } catch (PyException e) { - // Make this work like CPython where - // - // a = 7; len(a) raises a TypeError, - // a.__len__() raises an AttributeError - // and - // class F: pass - // f = F(); len(f) also raises an AttributeError - // - // Testing the type of o feels unclean though - if (e.type == Py.AttributeError && !(o instanceof PyInstance)) { - throw Py.TypeError("len() of unsized object"); - } - throw e; - } + public static int len(PyObject obj) { + return obj.__len__(); } public static PyObject locals() { @@ -1094,8 +1021,8 @@ return o.__repr__(); } - public static void setattr(PyObject o, String n, PyObject v) { - o.__setattr__(n, v); + public static void setattr(PyObject obj, PyObject name, PyObject value) { + obj.__setattr__(asName(name, "setattr"), value); } public static PyObject sum(PyObject seq, PyObject result) { @@ -1225,6 +1152,22 @@ fromlist, Py.newInteger(level)}); return module; } + + /** + * Return an interned String from name, raising a TypeError when conversion fails. + * + * @param name a PyObject + * @param function name of the python function caller + * @return an interned String + */ + private static String asName(PyObject name, String function) { + if (name instanceof PyUnicode) { + return ((PyUnicode)name).encode().intern(); + } else if (name instanceof PyString) { + return ((PyString)name).internedString(); + } + throw Py.TypeError(function + "(): attribute name must be string"); + } } class ImportFunction extends PyBuiltinFunction { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-28 03:05:07
|
Revision: 6923 http://jython.svn.sourceforge.net/jython/?rev=6923&view=rev Author: pjenvey Date: 2009-10-28 03:04:56 +0000 (Wed, 28 Oct 2009) Log Message: ----------- fix test_mode on Windows Modified Paths: -------------- trunk/jython/Lib/test/test_tempfile.py Modified: trunk/jython/Lib/test/test_tempfile.py =================================================================== --- trunk/jython/Lib/test/test_tempfile.py 2009-10-28 02:52:25 UTC (rev 6922) +++ trunk/jython/Lib/test/test_tempfile.py 2009-10-28 03:04:56 UTC (rev 6923) @@ -489,7 +489,7 @@ # mkdtemp creates directories with the proper mode if not has_stat: return # ugh, can't use TestSkipped. - if sys.platform.startswith('java') and not os._native_posix: + if test_support.is_jython and not os._native_posix: # Java doesn't support stating files for permissions return @@ -498,7 +498,8 @@ mode = stat.S_IMODE(os.stat(dir).st_mode) mode &= 0777 # Mask off sticky bits inherited from /tmp expected = 0700 - if sys.platform in ('win32', 'os2emx', 'mac'): + if (sys.platform in ('win32', 'os2emx', 'mac') or + test_support.is_jython and os._name == 'nt'): # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. user = expected >> 6 @@ -694,7 +695,8 @@ if __name__ == "__main__": test_main() - # XXX: Nudge Java's GC in an attempt to trigger any temp file's - # __del__ (cause them to be deleted) that hasn't been called - import gc - gc.collect() + if test_support.is_jython: + # XXX: Nudge Java's GC in an attempt to trigger any temp file's + # __del__ (cause them to be deleted) that hasn't been called + import gc + gc.collect() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-28 02:52:34
|
Revision: 6922 http://jython.svn.sourceforge.net/jython/?rev=6922&view=rev Author: pjenvey Date: 2009-10-28 02:52:25 +0000 (Wed, 28 Oct 2009) Log Message: ----------- changelog recent posix fixes Modified Paths: -------------- trunk/jython/NEWS Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-10-28 02:28:34 UTC (rev 6921) +++ trunk/jython/NEWS 2009-10-28 02:52:25 UTC (rev 6922) @@ -5,6 +5,9 @@ - [ 1478 ] defaultdict & weakref.WeakKeyDictionary [TypeError: first argument must be callable] - [ 1487 ] Import of module with latin-1 chars fails on utf-8 file encoding - [ 1449 ] Ellipsis comparison different from Python 2.5 to Jython 2.5 + - [ 1493 ] tarfile.extractall() throws "AttributeError: 'module' object has no attribute 'chown'" when called by root + - [ 1470 ] os.mkdir Errno difference from cpython + - [ 1496 ] fix os.listdir errno for non-existing dirs - Fix runtime issues during exitfuncs triggered via SystemRestart (such as during Django or Pylons development mode reloading) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-28 02:28:46
|
Revision: 6921 http://jython.svn.sourceforge.net/jython/?rev=6921&view=rev Author: pjenvey Date: 2009-10-28 02:28:34 +0000 (Wed, 28 Oct 2009) Log Message: ----------- o more over to PosixModule, so we don't need the builtin-in function class var workaround for tempfile refs #1396 o bring back the PosixModule method hider with hiding per OS and whether the posix impl is native Modified Paths: -------------- trunk/jython/CPythonLib.includes trunk/jython/Lib/posix.py trunk/jython/Lib/test/test_tempfile.py trunk/jython/src/org/python/modules/posix/PosixModule.java Added Paths: ----------- trunk/jython/src/org/python/modules/posix/Hider.java Removed Paths: ------------- trunk/jython/Lib/tempfile.py Modified: trunk/jython/CPythonLib.includes =================================================================== --- trunk/jython/CPythonLib.includes 2009-10-27 23:54:38 UTC (rev 6920) +++ trunk/jython/CPythonLib.includes 2009-10-28 02:28:34 UTC (rev 6921) @@ -134,6 +134,7 @@ tabnanny.py this.py textwrap.py +tempfile.py token.py tokenize.py trace.py Modified: trunk/jython/Lib/posix.py =================================================================== --- trunk/jython/Lib/posix.py 2009-10-27 23:54:38 UTC (rev 6920) +++ trunk/jython/Lib/posix.py 2009-10-28 02:28:34 UTC (rev 6921) @@ -14,8 +14,8 @@ import sys __all__ = [name for name in _posix.__all__ if not name.startswith('__doc__')] -__all__.extend(['fsync', 'getenv', 'getpid', 'isatty', 'popen', 'putenv', - 'remove', 'rename', 'rmdir', 'system', 'umask', 'unlink', +__all__.extend(['fsync', 'getenv', 'isatty', 'popen', 'putenv', + 'rename', 'rmdir', 'system', 'unsetenv', 'urandom', 'utime']) _name = _posix.__name__[1:] @@ -26,17 +26,6 @@ # For urandom urandom_source = None -def remove(path): - """remove(path) - - Remove a file (same as unlink(path)). - """ - from java.io import File - if not File(sys.getPath(path)).delete(): - raise OSError(0, "couldn't delete file", path) - -unlink = remove - def rename(path, newpath): """rename(old, new) @@ -181,13 +170,6 @@ return os.environ.get(key, default) if _name == 'posix': - def link(src, dst): - """link(src, dst) - - Create a hard link to a file. - """ - _posix_impl.link(sys.getPath(src), sys.getPath(dst)) - def symlink(src, dst): """symlink(src, dst) @@ -305,7 +287,7 @@ """ _fsync(fd, False) - __all__.extend(['link', 'symlink', 'readlink', 'getegid', 'geteuid', + __all__.extend(['symlink', 'readlink', 'getegid', 'geteuid', 'getgid', 'getlogin', 'getpgrp', 'getppid', 'getuid', 'setpgrp', 'setsid', 'kill', 'wait', 'waitpid', 'fdatasync']) @@ -334,14 +316,6 @@ except IOException, ioe: raise OSError(ioe) -def getpid(): - """getpid() -> pid - - Return the current process id.""" - # XXX: getpid and umask should really be hidden from __all__ when - # not _native_posix - return _posix_impl.getpid() - def isatty(fileno): """isatty(fd) -> bool @@ -371,12 +345,6 @@ return fileno.isatty() -def umask(new_mask): - """umask(new_mask) -> old_mask - - Set the current numeric umask and return the previous umask.""" - return _posix_impl.umask(int(new_mask)) - def urandom(n): global urandom_source if urandom_source is None: Deleted: trunk/jython/Lib/tempfile.py =================================================================== --- trunk/jython/Lib/tempfile.py 2009-10-27 23:54:38 UTC (rev 6920) +++ trunk/jython/Lib/tempfile.py 2009-10-28 02:28:34 UTC (rev 6921) @@ -1,494 +0,0 @@ -"""Temporary files. - -This module provides generic, low- and high-level interfaces for -creating temporary files and directories. The interfaces listed -as "safe" just below can be used without fear of race conditions. -Those listed as "unsafe" cannot, and are provided for backward -compatibility only. - -This module also provides some data items to the user: - - TMP_MAX - maximum number of names that will be tried before - giving up. - template - the default prefix for all temporary names. - You may change this to control the default prefix. - tempdir - If this is set to a string before the first use of - any routine from this module, it will be considered as - another candidate location to store temporary files. -""" - -__all__ = [ - "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces - "mkstemp", "mkdtemp", # low level safe interfaces - "mktemp", # deprecated unsafe interface - "TMP_MAX", "gettempprefix", # constants - "tempdir", "gettempdir" - ] - - -# Imports. - -import os as _os -import errno as _errno -from random import Random as _Random - -if _os.name == 'mac': - import Carbon.Folder as _Folder - import Carbon.Folders as _Folders - -try: - import fcntl as _fcntl -except ImportError: - def _set_cloexec(fd): - pass -else: - def _set_cloexec(fd): - try: - flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0) - except IOError: - pass - else: - # flags read successfully, modify - flags |= _fcntl.FD_CLOEXEC - _fcntl.fcntl(fd, _fcntl.F_SETFD, flags) - - -try: - import thread as _thread -except ImportError: - import dummy_thread as _thread -_allocate_lock = _thread.allocate_lock - -_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL -if hasattr(_os, 'O_NOINHERIT'): - _text_openflags |= _os.O_NOINHERIT -if hasattr(_os, 'O_NOFOLLOW'): - _text_openflags |= _os.O_NOFOLLOW - -_bin_openflags = _text_openflags -if hasattr(_os, 'O_BINARY'): - _bin_openflags |= _os.O_BINARY - -if hasattr(_os, 'TMP_MAX'): - TMP_MAX = _os.TMP_MAX -else: - TMP_MAX = 10000 - -template = "tmp" - -tempdir = None - -# Internal routines. - -_once_lock = _allocate_lock() - -if hasattr(_os, "lstat"): - _stat = _os.lstat -elif hasattr(_os, "stat"): - _stat = _os.stat -else: - # Fallback. All we need is something that raises os.error if the - # file doesn't exist. - def _stat(fn): - try: - f = open(fn) - except IOError: - raise _os.error - f.close() - -def _exists(fn): - try: - _stat(fn) - except _os.error: - return False - else: - return True - -class _RandomNameSequence: - """An instance of _RandomNameSequence generates an endless - sequence of unpredictable strings which can safely be incorporated - into file names. Each string is six characters long. Multiple - threads can safely use the same instance at the same time. - - _RandomNameSequence is an iterator.""" - - characters = ("abcdefghijklmnopqrstuvwxyz" + - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - "0123456789-_") - - def __init__(self): - self.mutex = _allocate_lock() - self.rng = _Random() - self.normcase = _os.path.normcase - - def __iter__(self): - return self - - def next(self): - m = self.mutex - c = self.characters - choose = self.rng.choice - - m.acquire() - try: - letters = [choose(c) for dummy in "123456"] - finally: - m.release() - - return self.normcase(''.join(letters)) - -def _candidate_tempdir_list(): - """Generate a list of candidate temporary directories which - _get_default_tempdir will try.""" - - dirlist = [] - - # First, try the environment. - for envname in 'TMPDIR', 'TEMP', 'TMP': - dirname = _os.getenv(envname) - if dirname: dirlist.append(dirname) - - # Failing that, try OS-specific locations. - if _os.name == 'mac': - try: - fsr = _Folder.FSFindFolder(_Folders.kOnSystemDisk, - _Folders.kTemporaryFolderType, 1) - dirname = fsr.as_pathname() - dirlist.append(dirname) - except _Folder.error: - pass - elif _os.name == 'riscos': - dirname = _os.getenv('Wimp$ScrapDir') - if dirname: dirlist.append(dirname) - elif _os.name == 'nt': - dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]) - else: - dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ]) - - # As a last resort, the current directory. - try: - dirlist.append(_os.getcwd()) - except (AttributeError, _os.error): - dirlist.append(_os.curdir) - - return dirlist - -def _get_default_tempdir(): - """Calculate the default directory to use for temporary files. - This routine should be called exactly once. - - We determine whether or not a candidate temp dir is usable by - trying to create and write to a file in that directory. If this - is successful, the test file is deleted. To prevent denial of - service, the name of the test file must be randomized.""" - - namer = _RandomNameSequence() - dirlist = _candidate_tempdir_list() - flags = _text_openflags - - for dir in dirlist: - if dir != _os.curdir: - dir = _os.path.normcase(_os.path.abspath(dir)) - # Try only a few names per directory. - for seq in xrange(100): - name = namer.next() - filename = _os.path.join(dir, name) - try: - fd = _os.open(filename, flags, 0600) - fp = _os.fdopen(fd, 'w') - fp.write('blat') - fp.close() - _os.unlink(filename) - del fp, fd - return dir - except (OSError, IOError), e: - if e[0] != _errno.EEXIST: - break # no point trying more names in this directory - pass - raise IOError, (_errno.ENOENT, - ("No usable temporary directory found in %s" % dirlist)) - -_name_sequence = None - -def _get_candidate_names(): - """Common setup sequence for all user-callable interfaces.""" - - global _name_sequence - if _name_sequence is None: - _once_lock.acquire() - try: - if _name_sequence is None: - _name_sequence = _RandomNameSequence() - finally: - _once_lock.release() - return _name_sequence - - -def _mkstemp_inner(dir, pre, suf, flags): - """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" - - names = _get_candidate_names() - - for seq in xrange(TMP_MAX): - name = names.next() - file = _os.path.join(dir, pre + name + suf) - try: - fd = _os.open(file, flags, 0600) - _set_cloexec(fd) - return (fd, _os.path.abspath(file)) - except OSError, e: - if e.errno == _errno.EEXIST: - continue # try again - raise - - raise IOError, (_errno.EEXIST, "No usable temporary file name found") - - -# User visible interfaces. - -def gettempprefix(): - """Accessor for tempdir.template.""" - return template - -tempdir = None - -def gettempdir(): - """Accessor for tempdir.tempdir.""" - global tempdir - if tempdir is None: - _once_lock.acquire() - try: - if tempdir is None: - tempdir = _get_default_tempdir() - finally: - _once_lock.release() - return tempdir - -def mkstemp(suffix="", prefix=template, dir=None, text=False): - """mkstemp([suffix, [prefix, [dir, [text]]]]) - User-callable function to create and return a unique temporary - file. The return value is a pair (fd, name) where fd is the - file descriptor returned by os.open, and name is the filename. - - If 'suffix' is specified, the file name will end with that suffix, - otherwise there will be no suffix. - - If 'prefix' is specified, the file name will begin with that prefix, - otherwise a default prefix is used. - - If 'dir' is specified, the file will be created in that directory, - otherwise a default directory is used. - - If 'text' is specified and true, the file is opened in text - mode. Else (the default) the file is opened in binary mode. On - some operating systems, this makes no difference. - - The file is readable and writable only by the creating user ID. - If the operating system uses permission bits to indicate whether a - file is executable, the file is executable by no one. The file - descriptor is not inherited by children of this process. - - Caller is responsible for deleting the file when done with it. - """ - - if dir is None: - dir = gettempdir() - - if text: - flags = _text_openflags - else: - flags = _bin_openflags - - return _mkstemp_inner(dir, prefix, suffix, flags) - - -def mkdtemp(suffix="", prefix=template, dir=None): - """mkdtemp([suffix, [prefix, [dir]]]) - User-callable function to create and return a unique temporary - directory. The return value is the pathname of the directory. - - Arguments are as for mkstemp, except that the 'text' argument is - not accepted. - - The directory is readable, writable, and searchable only by the - creating user. - - Caller is responsible for deleting the directory when done with it. - """ - - if dir is None: - dir = gettempdir() - - names = _get_candidate_names() - - for seq in xrange(TMP_MAX): - name = names.next() - file = _os.path.join(dir, prefix + name + suffix) - try: - _os.mkdir(file, 0700) - return file - except OSError, e: - if e.errno == _errno.EEXIST: - continue # try again - raise - - raise IOError, (_errno.EEXIST, "No usable temporary directory name found") - -def mktemp(suffix="", prefix=template, dir=None): - """mktemp([suffix, [prefix, [dir]]]) - User-callable function to return a unique temporary file name. The - file is not created. - - Arguments are as for mkstemp, except that the 'text' argument is - not accepted. - - This function is unsafe and should not be used. The file name - refers to a file that did not exist at some point, but by the time - you get around to creating it, someone else may have beaten you to - the punch. - """ - -## from warnings import warn as _warn -## _warn("mktemp is a potential security risk to your program", -## RuntimeWarning, stacklevel=2) - - if dir is None: - dir = gettempdir() - - names = _get_candidate_names() - for seq in xrange(TMP_MAX): - name = names.next() - file = _os.path.join(dir, prefix + name + suffix) - if not _exists(file): - return file - - raise IOError, (_errno.EEXIST, "No usable temporary filename found") - -class _TemporaryFileWrapper: - """Temporary file wrapper - - This class provides a wrapper around files opened for - temporary use. In particular, it seeks to automatically - remove the file when it is no longer needed. - """ - - def __init__(self, file, name): - self.file = file - self.name = name - self.close_called = False - - # XXX: CPython assigns unlink as a class var but this would - # rebind Jython's os.unlink (to be a classmethod) because it's - # not a built-in function (unfortunately built-in functions act - # differently when binding: - # http://mail.python.org/pipermail/python-dev/2003-April/034749.html) - - # Cache the unlinker so we don't get spurious errors at - # shutdown when the module-level "os" is None'd out. Note - # that this must be referenced as self.unlink, because the - # name TemporaryFileWrapper may also get None'd out before - # __del__ is called. - self.unlink = _os.unlink - - def __getattr__(self, name): - # Attribute lookups are delegated to the underlying file - # and cached for non-numeric results - # (i.e. methods are cached, closed and friends are not) - file = self.__dict__['file'] - a = getattr(file, name) - if type(a) != type(0): - setattr(self, name, a) - return a - - # The underlying __enter__ method returns the wrong object - # (self.file) so override it to return the wrapper - def __enter__(self): - self.file.__enter__() - return self - - # NT provides delete-on-close as a primitive, so we don't need - # the wrapper to do anything special. We still use it so that - # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile. - if _os.name != 'nt': - def close(self): - if not self.close_called: - self.close_called = True - self.file.close() - self.unlink(self.name) - - def __del__(self): - self.close() - - # Need to trap __exit__ as well to ensure the file gets - # deleted when used in a with statement - def __exit__(self, exc, value, tb): - result = self.file.__exit__(exc, value, tb) - self.close() - return result - - -def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="", - prefix=template, dir=None): - """Create and return a temporary file. - Arguments: - 'prefix', 'suffix', 'dir' -- as for mkstemp. - 'mode' -- the mode argument to os.fdopen (default "w+b"). - 'bufsize' -- the buffer size argument to os.fdopen (default -1). - The file is created as mkstemp() would do it. - - Returns an object with a file-like interface; the name of the file - is accessible as file.name. The file will be automatically deleted - when it is closed. - """ - - if dir is None: - dir = gettempdir() - - if 'b' in mode: - flags = _bin_openflags - else: - flags = _text_openflags - - # Setting O_TEMPORARY in the flags causes the OS to delete - # the file when it is closed. This is only supported by Windows. - if _os.name == 'nt': - flags |= _os.O_TEMPORARY - - (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) - file = _os.fdopen(fd, mode, bufsize) - return _TemporaryFileWrapper(file, name) - -if _os.name != 'posix' or _os.sys.platform == 'cygwin': - # On non-POSIX and Cygwin systems, assume that we cannot unlink a file - # while it is open. - TemporaryFile = NamedTemporaryFile - -else: - def TemporaryFile(mode='w+b', bufsize=-1, suffix="", - prefix=template, dir=None): - """Create and return a temporary file. - Arguments: - 'prefix', 'suffix', 'dir' -- as for mkstemp. - 'mode' -- the mode argument to os.fdopen (default "w+b"). - 'bufsize' -- the buffer size argument to os.fdopen (default -1). - The file is created as mkstemp() would do it. - - Returns an object with a file-like interface. The file has no - name, and will cease to exist when it is closed. - """ - - if dir is None: - dir = gettempdir() - - if 'b' in mode: - flags = _bin_openflags - else: - flags = _text_openflags - - (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) - try: - _os.unlink(name) - return _os.fdopen(fd, mode, bufsize) - except: - _os.close(fd) - raise Modified: trunk/jython/Lib/test/test_tempfile.py =================================================================== --- trunk/jython/Lib/test/test_tempfile.py 2009-10-27 23:54:38 UTC (rev 6920) +++ trunk/jython/Lib/test/test_tempfile.py 2009-10-28 02:28:34 UTC (rev 6921) @@ -208,18 +208,13 @@ class mkstemped: _bflags = tempfile._bin_openflags _tflags = tempfile._text_openflags + _close = os.close + _unlink = os.unlink def __init__(self, dir, pre, suf, bin): if bin: flags = self._bflags else: flags = self._tflags - # XXX: CPython assigns _close/_unlink as class vars but this - # would rebind Jython's close/unlink (to be classmethods) - # because they're not built-in functions (unfortunately - # built-in functions act differently when binding: - # http://mail.python.org/pipermail/python-dev/2003-April/034749.html) - self._close = os.close - self._unlink = os.unlink (self.fd, self.name) = tempfile._mkstemp_inner(dir, pre, suf, flags) def write(self, str): @@ -494,7 +489,7 @@ # mkdtemp creates directories with the proper mode if not has_stat: return # ugh, can't use TestSkipped. - if os.name == 'java': + if sys.platform.startswith('java') and not os._native_posix: # Java doesn't support stating files for permissions return @@ -529,13 +524,10 @@ self.dir = None class mktemped: + _unlink = os.unlink _bflags = tempfile._bin_openflags def __init__(self, dir, pre, suf): - # XXX: Assign _unlink here, instead of as a class var. See - # mkstemped.__init__ for an explanation - self._unlink = os.unlink - self.name = tempfile.mktemp(dir=dir, prefix=pre, suffix=suf) # Create the file. This will raise an exception if it's # mysteriously appeared in the meanwhile. @@ -704,5 +696,5 @@ test_main() # XXX: Nudge Java's GC in an attempt to trigger any temp file's # __del__ (cause them to be deleted) that hasn't been called - from java.lang import System - System.gc() + import gc + gc.collect() Added: trunk/jython/src/org/python/modules/posix/Hider.java =================================================================== --- trunk/jython/src/org/python/modules/posix/Hider.java (rev 0) +++ trunk/jython/src/org/python/modules/posix/Hider.java 2009-10-28 02:28:34 UTC (rev 6921) @@ -0,0 +1,75 @@ +/* Copyright (c) Jython Developers */ +package org.python.modules.posix; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.reflect.Method; + +import org.python.core.PyObject; + +/** + * Utility class for hiding PosixModule methods depending on the platform, or whether the + * underlying posix implementation is native. + */ +class Hider { + + /** + * Hide module level functions defined in the PosixModule dict not applicable to this + * OS, identified by the PosixModule.Hide annotation. + * + * @param cls the PosixModule class + * @param dict the PosixModule module dict + * @param os the underlying OS + * @param native whether the underlying posix is native + */ + public static void hideFunctions(Class<?> cls, PyObject dict, OS os, boolean isNative) { + for (Method method: cls.getDeclaredMethods()) { + if (isHidden(method, os, isNative ? PosixImpl.NATIVE : PosixImpl.JAVA)) { + dict.__setitem__(method.getName(), null); + } + } + } + + /** + * Determine if method should be hidden for this OS/PosixImpl. + */ + private static boolean isHidden(Method method, OS os, PosixImpl posixImpl) { + if (method.isAnnotationPresent(Hide.class)) { + Hide hide = method.getAnnotation(Hide.class); + if (hide.posixImpl() != PosixImpl.NOT_APPLICABLE && hide.posixImpl() == posixImpl) { + return true; + } + for (OS hideOS : hide.value()) { + if (os == hideOS) { + return true; + } + } + } + return false; + } +} + +/** + * Tags PosixModule methods as hidden on the specified OS or PosixImpl. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@interface Hide { + + /** Hide method on these OSes. */ + OS[] value() default {}; + + /** + * @Hide(posixImpl = PosixImpl.JAVA) hides the method from Python when the POSIX + * library isn't native. The default NOT_APPLICABLE means the POSIX implementation + * doesn't matter. + */ + PosixImpl posixImpl() default PosixImpl.NOT_APPLICABLE; +} + +/** + * The type of underlying POSIX library implementation (native or not). + */ +enum PosixImpl {NOT_APPLICABLE, NATIVE, JAVA}; Modified: trunk/jython/src/org/python/modules/posix/PosixModule.java =================================================================== --- trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-27 23:54:38 UTC (rev 6920) +++ trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-28 02:28:34 UTC (rev 6921) @@ -92,13 +92,15 @@ // Successful termination dict.__setitem__("EX_OK", Py.Zero); + boolean nativePosix = !(posix instanceof JavaPOSIX); + dict.__setitem__("_native_posix", Py.newBoolean(nativePosix)); + dict.__setitem__("_posix_impl", Py.java2py(posix)); dict.__setitem__("environ", getEnviron()); dict.__setitem__("error", Py.OSError); dict.__setitem__("stat_result", PyStatResult.TYPE); - dict.__setitem__("_posix_impl", Py.java2py(posix)); - dict.__setitem__("_native_posix", Py.newBoolean(!(posix instanceof JavaPOSIX))); // Hide from Python + Hider.hideFunctions(PosixModule.class, dict, os, nativePosix); dict.__setitem__("classDictInit", null); dict.__setitem__("getPOSIX", null); dict.__setitem__("getOSName", null); @@ -190,6 +192,7 @@ public static PyString __doc__chown = new PyString( "chown(path, uid, gid)\n\n" + "Change the owner and group id of path to the numeric uid and gid."); + @Hide(OS.POSIX) public static void chown(String path, int uid, int gid) { if (posix.chown(absolutePath(path), uid, gid) < 0) { throw errorFromErrno(path); @@ -263,6 +266,22 @@ return Py.newUnicode(Py.getSystemState().getCurrentWorkingDir()); } + public static PyString __doc___getpid = new PyString( + "getpid() -> pid\n\n" + + "Return the current process id"); + @Hide(posixImpl = PosixImpl.JAVA) + public static int getpid() { + return posix.getpid(); + } + + public static PyString __doc__link = new PyString( + "link(src, dst)\n\n" + + "Create a hard link to a file."); + @Hide(OS.NT) + public static void link(String src, String dst) { + posix.link(absolutePath(src), absolutePath(dst)); + } + public static PyString __doc__listdir = new PyString( "listdir(path) -> list_of_strings\n\n" + "Return a list containing the names of the entries in the directory.\n\n" + @@ -286,7 +305,6 @@ if (!file.canRead()) { throw Py.OSError(Errno.EACCES, path); } - // throw Py.OSError("listdir(): an unknown error occured: " + path); } for (String name : names) { @@ -399,6 +417,13 @@ } } + public static PyString __doc__remove = new PyString( + "remove(path)\n\n" + + "Remove a file (same as unlink(path))."); + public static void remove(String path) { + unlink(path); + } + public static PyString __doc__stat = new PyString( "stat(path) -> stat result\n\n" + "Perform a stat system call on the given path.\n\n" + @@ -425,6 +450,34 @@ return new PyString(errno.toString()); } + public static PyString __doc__umask = new PyString( + "umask(new_mask) -> old_mask\n\n" + + "Set the current numeric umask and return the previous umask."); + @Hide(posixImpl = PosixImpl.JAVA) + public static int umask(int mask) { + return posix.umask(mask); + } + + public static PyString __doc__unlink = new PyString( + "unlink(path)\n\n" + + "Remove a file (same as remove(path))."); + public static void unlink(String path) { + ensurePath(path); + File file = new RelativeFile(path); + if (!file.delete()) { + // Something went wrong, does stat raise an error? + posix.stat(absolutePath(path)); + // It exists, is it a directory, or do we not have permissions? + if (file.isDirectory()) { + throw Py.OSError(Errno.EISDIR, path); + } + if (!file.canWrite()) { + throw Py.OSError(Errno.EPERM, path); + } + throw Py.OSError("unlink(): an unknown error occured: " + path); + } + } + public static PyString __doc__write = new PyString( "write(fd, string) -> byteswritten\n\n" + "Write a string to a file descriptor."); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-27 23:55:02
|
Revision: 6920 http://jython.svn.sourceforge.net/jython/?rev=6920&view=rev Author: pjenvey Date: 2009-10-27 23:54:38 +0000 (Tue, 27 Oct 2009) Log Message: ----------- o move chmod/mkdir to PosixModule and add chown, using the newer jna-posix errno() for accurate error messages fixes #1470, 1493 o attempt to figure out listdir failure errnos fixes #1496 o guard against null paths in PosixModule refs #1369 Modified Paths: -------------- trunk/jython/Lib/posix.py trunk/jython/src/org/python/modules/posix/PosixModule.java Modified: trunk/jython/Lib/posix.py =================================================================== --- trunk/jython/Lib/posix.py 2009-10-27 23:49:37 UTC (rev 6919) +++ trunk/jython/Lib/posix.py 2009-10-27 23:54:38 UTC (rev 6920) @@ -14,9 +14,9 @@ import sys __all__ = [name for name in _posix.__all__ if not name.startswith('__doc__')] -__all__.extend(['chmod', 'fsync', 'getenv', 'getpid', 'isatty', 'mkdir', - 'popen', 'putenv', 'remove', 'rename', 'rmdir', 'system', - 'umask', 'unlink', 'unsetenv', 'urandom', 'utime']) +__all__.extend(['fsync', 'getenv', 'getpid', 'isatty', 'popen', 'putenv', + 'remove', 'rename', 'rmdir', 'system', 'umask', 'unlink', + 'unsetenv', 'urandom', 'utime']) _name = _posix.__name__[1:] @@ -26,37 +26,6 @@ # For urandom urandom_source = None -def chmod(path, mode): - """chmod(path, mode) - - Change the access permissions of a file. - """ - # XXX no error handling for chmod in jna-posix - # catch not found errors explicitly here, for now - from java.io import File - abs_path = sys.getPath(path) - if not File(abs_path).exists(): - raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) - _posix_impl.chmod(abs_path, mode) - -def mkdir(path, mode='ignored'): - """mkdir(path [, mode=0777]) - - Create a directory. - - The optional parameter is currently ignored. - """ - # XXX: use _posix_impl.mkdir when we can get the real errno upon failure - from java.io import File - fp = File(sys.getPath(path)) - if not fp.mkdir(): - if fp.isDirectory() or fp.isFile(): - err = errno.EEXIST - else: - err = 0 - msg = strerror(err) if err else "couldn't make directory" - raise OSError(err, msg, path) - def remove(path): """remove(path) @@ -369,6 +338,8 @@ """getpid() -> pid Return the current process id.""" + # XXX: getpid and umask should really be hidden from __all__ when + # not _native_posix return _posix_impl.getpid() def isatty(fileno): Modified: trunk/jython/src/org/python/modules/posix/PosixModule.java =================================================================== --- trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-27 23:49:37 UTC (rev 6919) +++ trunk/jython/src/org/python/modules/posix/PosixModule.java 2009-10-27 23:54:38 UTC (rev 6920) @@ -11,6 +11,7 @@ import java.nio.ByteBuffer; import java.util.Map; +import org.jruby.ext.posix.FileStat; import org.jruby.ext.posix.JavaPOSIX; import org.jruby.ext.posix.POSIX; import org.jruby.ext.posix.POSIXFactory; @@ -128,6 +129,7 @@ "specified access to the path. The mode argument can be F_OK to test\n" + "existence, or the inclusive-OR of R_OK, W_OK, and X_OK."); public static boolean access(String path, int mode) { + ensurePath(path); boolean result = true; File file = new RelativeFile(path); @@ -166,7 +168,7 @@ String path = pathObj.toString(); // stat raises ENOENT for us if path doesn't exist - if (!posix.stat(new RelativeFile(path).getPath()).isDirectory()) { + if (!posix.stat(absolutePath(path)).isDirectory()) { throw Py.OSError(Errno.ENOTDIR, path); } @@ -176,6 +178,24 @@ Py.getSystemState().setCurrentWorkingDir(realpath.__call__(pathObj).toString()); } + public static PyString __doc__chmod = new PyString( + "chmod(path, mode)\n\n" + + "Change the access permissions of a file."); + public static void chmod(String path, int mode) { + if (posix.chmod(absolutePath(path), mode) < 0) { + throw errorFromErrno(path); + } + } + + public static PyString __doc__chown = new PyString( + "chown(path, uid, gid)\n\n" + + "Change the owner and group id of path to the numeric uid and gid."); + public static void chown(String path, int uid, int gid) { + if (posix.chown(absolutePath(path), uid, gid) < 0) { + throw errorFromErrno(path); + } + } + public static PyString __doc__close = new PyString( "close(fd)\n\n" + "Close a file descriptor (for low level IO)."); @@ -183,7 +203,7 @@ try { FileDescriptors.get(fd).close(); } catch (PyException pye) { - badFD(); + throw badFD(); } } @@ -205,7 +225,7 @@ } RawIOBase rawIO = FileDescriptors.get(fd); if (rawIO.closed()) { - badFD(); + throw badFD(); } try { @@ -250,14 +270,27 @@ "The list is in arbitrary order. It does not include the special\n" + "entries '.' and '..' even if they are present in the directory."); public static PyList listdir(String path) { + ensurePath(path); PyList list = new PyList(); - String[] files = new RelativeFile(path).list(); + File file = new RelativeFile(path); + String[] names = file.list(); - if (files == null) { - throw Py.OSError("No such directory: " + path); + if (names == null) { + // Can't read the path for some reason. stat will throw an error if it can't + // read it either + FileStat stat = posix.stat(file.getPath()); + // It exists, maybe not a dir, or we don't have permission? + if (!stat.isDirectory()) { + throw Py.OSError(Errno.ENOTDIR, path); + } + if (!file.canRead()) { + throw Py.OSError(Errno.EACCES, path); + } + // + throw Py.OSError("listdir(): an unknown error occured: " + path); } - for (String file : files) { - list.append(new PyString(file)); + for (String name : names) { + list.append(new PyString(name)); } return list; } @@ -269,8 +302,7 @@ try { return FileDescriptors.get(fd).seek(pos, how); } catch (PyException pye) { - badFD(); - return -1; + throw badFD(); } } @@ -278,9 +310,22 @@ "lstat(path) -> stat result\n\n" + "Like stat(path), but do not follow symbolic links."); public static PyObject lstat(String path) { - return PyStatResult.fromFileStat(posix.lstat(new RelativeFile(path).getPath())); + return PyStatResult.fromFileStat(posix.lstat(absolutePath(path))); } + public static PyString __doc__mkdir = new PyString( + "mkdir(path [, mode=0777])\n\n" + + "Create a directory."); + public static void mkdir(String path) { + mkdir(path, 0777); + } + + public static void mkdir(String path, int mode) { + if (posix.mkdir(absolutePath(path), mode) < 0) { + throw errorFromErrno(path); + } + } + public static PyString __doc__open = new PyString( "open(filename, flag [, mode=0777]) -> fd\n\n" + "Open a file (for low level IO).\n\n" + @@ -290,6 +335,7 @@ } public static FileIO open(String path, int flag, int mode) { + ensurePath(path); boolean reading = (flag & O_RDONLY) != 0; boolean writing = (flag & O_WRONLY) != 0; boolean updating = (flag & O_RDWR) != 0; @@ -349,8 +395,7 @@ try { return StringUtil.fromBytes(FileDescriptors.get(fd).read(buffersize)); } catch (PyException pye) { - badFD(); - return null; + throw badFD(); } } @@ -360,7 +405,7 @@ "Note that some platforms may return only a small subset of the\n" + "standard fields"); public static PyObject stat(String path) { - return PyStatResult.fromFileStat(posix.stat(new RelativeFile(path).getPath())); + return PyStatResult.fromFileStat(posix.stat(absolutePath(path))); } public static PyString __doc__strerror = new PyString( @@ -387,8 +432,7 @@ try { return FileDescriptors.get(fd).write(ByteBuffer.wrap(StringUtil.toBytes(string))); } catch (PyException pye) { - badFD(); - return -1; + throw badFD(); } } @@ -430,10 +474,31 @@ return environ; } - private static void badFD() { - throw Py.OSError(Errno.EBADF); + /** + * Return the absolute form of path. + * + * @param path a path String, raising a TypeError when null + * @return an absolute path String + */ + private static String absolutePath(String path) { + ensurePath(path); + return new RelativeFile(path).getPath(); } + private static void ensurePath(String path) { + if (path == null) { + throw Py.TypeError("coercing to Unicode: need string or buffer, NoneType found"); + } + } + + private static PyException badFD() { + return Py.OSError(Errno.EBADF); + } + + private static PyException errorFromErrno(String path) { + return Py.OSError(Errno.valueOf(posix.errno()), path); + } + public static POSIX getPOSIX() { return posix; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-27 23:49:55
|
Revision: 6919 http://jython.svn.sourceforge.net/jython/?rev=6919&view=rev Author: pjenvey Date: 2009-10-27 23:49:37 +0000 (Tue, 27 Oct 2009) Log Message: ----------- simplify Modified Paths: -------------- trunk/jython/src/org/python/core/codecs.java Modified: trunk/jython/src/org/python/core/codecs.java =================================================================== --- trunk/jython/src/org/python/core/codecs.java 2009-10-27 22:21:57 UTC (rev 6918) +++ trunk/jython/src/org/python/core/codecs.java 2009-10-27 23:49:37 UTC (rev 6919) @@ -7,12 +7,13 @@ */ package org.python.core; -import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Iterator; +import org.python.core.util.StringUtil; + /** * Contains the implementation of the builtin codecs. * @since Jython 2.0 @@ -805,17 +806,7 @@ } public static String PyUnicode_EncodeUTF8(String str, String errors) { - final Charset utf8 = Charset.forName("UTF-8"); - final ByteBuffer bbuf = utf8.encode(str); - final StringBuilder v = new StringBuilder(bbuf.limit()); - while (bbuf.remaining() > 0) { - int val = bbuf.get(); - if (val < 0) { - val = 256 + val; - } - v.appendCodePoint(val); - } - return v.toString(); + return StringUtil.fromBytes(Charset.forName("UTF-8").encode(str)); } public static String PyUnicode_DecodeASCII(String str, int size, String errors) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-27 22:22:21
|
Revision: 6918 http://jython.svn.sourceforge.net/jython/?rev=6918&view=rev Author: pjenvey Date: 2009-10-27 22:21:57 +0000 (Tue, 27 Oct 2009) Log Message: ----------- has_key -> in, etc Modified Paths: -------------- trunk/jython/Lib/select.py trunk/jython/Lib/socket.py Modified: trunk/jython/Lib/select.py =================================================================== --- trunk/jython/Lib/select.py 2009-10-27 22:16:17 UTC (rev 6917) +++ trunk/jython/Lib/select.py 2009-10-27 22:21:57 UTC (rev 6918) @@ -117,7 +117,7 @@ else: try: timeout = int(timeout) - if timeout == 0: + if not timeout: self.selector.selectNow() else: # No multiplication required: both cpython and java use millisecond timeouts @@ -224,7 +224,7 @@ registered_for_read[fd] = 1 # And now the write list for fd in write_fd_list: - if registered_for_read.has_key(fd): + if fd in registered_for_read: # registering a second time overwrites the first pobj.register(fd, POLLIN|POLLOUT) else: Modified: trunk/jython/Lib/socket.py =================================================================== --- trunk/jython/Lib/socket.py 2009-10-27 22:16:17 UTC (rev 6917) +++ trunk/jython/Lib/socket.py 2009-10-27 22:21:57 UTC (rev 6918) @@ -259,7 +259,7 @@ self.jsocket.setSoTimeout(self._timeout_millis) def getsockopt(self, level, option): - if self.options.has_key( (level, option) ): + if (level, option) in self.options: result = getattr(self.jsocket, "get%s" % self.options[ (level, option) ])() if option == SO_LINGER: if result == -1: @@ -272,7 +272,7 @@ raise error(errno.ENOPROTOOPT, "Socket option '%s' (level '%s') not supported on socket(%s)" % (_constant_to_name(option), _constant_to_name(level), str(self.jsocket))) def setsockopt(self, level, option, value): - if self.options.has_key( (level, option) ): + if (level, option) in self.options: if option == SO_LINGER: values = struct.unpack('ii', value) self.jsocket.setSoLinger(*values) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-27 22:16:29
|
Revision: 6917 http://jython.svn.sourceforge.net/jython/?rev=6917&view=rev Author: pjenvey Date: 2009-10-27 22:16:17 +0000 (Tue, 27 Oct 2009) Log Message: ----------- is{Number,Mapping,Sequence}Type are unnecessary for PyNone now Modified Paths: -------------- trunk/jython/Lib/test/test_operator_jy.py trunk/jython/src/org/python/core/PyNone.java Modified: trunk/jython/Lib/test/test_operator_jy.py =================================================================== --- trunk/jython/Lib/test/test_operator_jy.py 2009-10-27 22:09:16 UTC (rev 6916) +++ trunk/jython/Lib/test/test_operator_jy.py 2009-10-27 22:16:17 UTC (rev 6917) @@ -44,6 +44,8 @@ (2L, True, False, False), (3.0, True, False, False), (4j, True, False, False), + (None, False, False, False), + (Ellipsis, False, False, False), (Exception(), False, False, True), (collections.deque(), False, False, True), (collections.defaultdict(), False, True, False), Modified: trunk/jython/src/org/python/core/PyNone.java =================================================================== --- trunk/jython/src/org/python/core/PyNone.java 2009-10-27 22:09:16 UTC (rev 6916) +++ trunk/jython/src/org/python/core/PyNone.java 2009-10-27 22:16:17 UTC (rev 6917) @@ -1,4 +1,7 @@ -// Copyright (c) Corporation for National Research Initiatives +/* + * Copyright (c) Corporation for National Research Initiatives + * Copyright (c) Jython Developers + */ package org.python.core; import java.io.Serializable; @@ -7,11 +10,10 @@ import org.python.expose.ExposedType; /** - * A class representing the singleton None object, + * The singleton None object. */ @ExposedType(name = "NoneType", isBaseType = false) -public class PyNone extends PyObject implements Serializable -{ +public class PyNone extends PyObject implements Serializable { public static final PyType TYPE = PyType.fromClass(PyNone.class); @@ -19,24 +21,25 @@ super(TYPE); } - private Object writeReplace() { - return new Py.SingletonResolver("None"); - } - + @Override public boolean __nonzero__() { return false; } - public Object __tojava__(Class c) { - //Danger here. java.lang.Object gets null not None - if (c == PyObject.class) + @Override + public Object __tojava__(Class<?> c) { + if (c == PyObject.class) { return this; - if (c.isPrimitive()) + } + if (c.isPrimitive()) { return Py.NoConversion; + } + // Java gets null return null; } - public String toString() throws PyIgnoreMethodTag { + @Override + public String toString() { return NoneType_toString(); } @@ -45,23 +48,17 @@ return "None"; } - public boolean isMappingType() { - return false; - } - - public boolean isSequenceType() { - return false; - } - - public boolean isNumberType() { - return false; - } - + @Override public String asStringOrNull(int index) { return null; } + @Override public String asStringOrNull() { return null; } + + private Object writeReplace() { + return new Py.SingletonResolver("None"); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-27 22:09:34
|
Revision: 6916 http://jython.svn.sourceforge.net/jython/?rev=6916&view=rev Author: pjenvey Date: 2009-10-27 22:09:16 +0000 (Tue, 27 Oct 2009) Log Message: ----------- coding standards/cleanup, avoid a potential ClassCastException in apply Modified Paths: -------------- trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2009-10-27 21:30:30 UTC (rev 6915) +++ trunk/jython/src/org/python/core/__builtin__.java 2009-10-27 22:09:16 UTC (rev 6916) @@ -1,6 +1,12 @@ -// Copyright (c) Corporation for National Research Initiatives +/* + * Copyright (c) Corporation for National Research Initiatives + * Copyright (c) Jython Developers + */ package org.python.core; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; @@ -47,20 +53,24 @@ public PyObject __call__(PyObject arg1) { switch (this.index) { case 0: - return Py.newString(__builtin__.chr(Py.py2int(arg1, "chr(): 1st arg can't be coerced to int"))); + return Py.newString(__builtin__.chr(Py.py2int(arg1, + "chr(): 1st arg can't be coerced to " + + "int"))); case 1: return Py.newInteger(__builtin__.len(arg1)); case 2: return __builtin__.range(arg1); case 3: if (!(arg1 instanceof PyString)) { - throw Py.TypeError("ord() expected string of length 1, but " + arg1.getType().fastGetName() + " found"); + throw Py.TypeError("ord() expected string of length 1, but " + + arg1.getType().fastGetName() + " found"); } return Py.newInteger(__builtin__.ord(arg1)); case 5: return __builtin__.hash(arg1); case 6: - return Py.newUnicode(__builtin__.unichr(Py.py2int(arg1, "unichr(): 1st arg can't be coerced to int"))); + return Py.newUnicode(__builtin__.unichr(Py.py2int(arg1, "unichr(): 1st arg can't " + + "be coerced to int"))); case 7: return __builtin__.abs(arg1); case 9: @@ -111,11 +121,11 @@ case 41: return __builtin__.vars(arg1); case 30: - return fancyCall(new PyObject[]{arg1}); + return fancyCall(new PyObject[] {arg1}); case 31: - return fancyCall(new PyObject[]{arg1}); + return fancyCall(new PyObject[] {arg1}); case 43: - return fancyCall(new PyObject[]{arg1}); + return fancyCall(new PyObject[] {arg1}); case 45: return __builtin__.reversed(arg1); default: @@ -139,7 +149,8 @@ case 13: return __builtin__.coerce(arg1, arg2); case 15: - __builtin__.delattr(arg1, asString(arg2, "delattr(): attribute name must be string")); + __builtin__.delattr(arg1, asString(arg2, + "delattr(): attribute name must be string")); return Py.None; case 17: return __builtin__.divmod(arg1, arg2); @@ -167,13 +178,13 @@ case 35: return __builtin__.reduce(arg1, arg2); case 29: - return fancyCall(new PyObject[]{arg1, arg2}); + return fancyCall(new PyObject[] {arg1, arg2}); case 30: - return fancyCall(new PyObject[]{arg1, arg2}); + return fancyCall(new PyObject[] {arg1, arg2}); case 31: - return fancyCall(new PyObject[]{arg1, arg2}); + return fancyCall(new PyObject[] {arg1, arg2}); case 43: - return fancyCall(new PyObject[]{arg1, arg2}); + return fancyCall(new PyObject[] {arg1, arg2}); default: throw info.unexpectedCall(2, false); } @@ -197,12 +208,14 @@ PyDictionary d = (PyDictionary) arg3; return __builtin__.apply(arg1, arg2, d); } catch (ClassCastException e) { - throw Py.TypeError("apply() 3rd argument must be a " + "dictionary with string keys"); + throw Py.TypeError("apply() 3rd argument must be a " + + "dictionary with string keys"); } case 18: return __builtin__.eval(arg1, arg2, arg3); case 19: - __builtin__.execfile(asString(arg1, "execfile's first argument must be str", false), arg2, arg3); + __builtin__.execfile(asString(arg1, "execfile's first argument must be str", + false), arg2, arg3); return Py.None; case 21: return __builtin__.getattr(arg1, arg2, arg3); @@ -211,25 +224,28 @@ case 35: return __builtin__.reduce(arg1, arg2, arg3); case 39: - __builtin__.setattr(arg1, asString(arg2, "setattr(): attribute name must be string"), arg3); + __builtin__.setattr(arg1, asString(arg2, + "setattr(): attribute name must be string"), + arg3); return Py.None; case 44: - return fancyCall(new PyObject[]{arg1, arg2, arg3}); + return fancyCall(new PyObject[] {arg1, arg2, arg3}); case 29: - return fancyCall(new PyObject[]{arg1, arg2, arg3}); + return fancyCall(new PyObject[] {arg1, arg2, arg3}); case 30: - return fancyCall(new PyObject[]{arg1, arg2, arg3}); + return fancyCall(new PyObject[] {arg1, arg2, arg3}); case 31: - return fancyCall(new PyObject[]{arg1, arg2, arg3}); + return fancyCall(new PyObject[] {arg1, arg2, arg3}); case 43: - return fancyCall(new PyObject[]{arg1, arg2, arg3}); + return fancyCall(new PyObject[] {arg1, arg2, arg3}); default: throw info.unexpectedCall(3, false); } } /** - * @return arg as an interned String, or throws TypeError with mesage if asString throws a ConversionException + * @return arg as an interned String, or throws TypeError with mesage if asString + * throws a ConversionException */ private String asString(PyObject arg, String message) { return asString(arg, message, true); @@ -237,7 +253,8 @@ /** * @param intern - should the resulting string be interned - * @return arg as a String, or throws TypeError with message if asString throws a ConversionException. + * @return arg as a String, or throws TypeError with message if asString throws a + * ConversionException. */ private String asString(PyObject arg, String message, boolean intern) { @@ -252,15 +269,15 @@ public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4) { switch (this.index) { case 44: - return fancyCall(new PyObject[]{arg1, arg2, arg3, arg4}); + return fancyCall(new PyObject[] {arg1, arg2, arg3, arg4}); case 29: - return fancyCall(new PyObject[]{arg1, arg2, arg3, arg4}); + return fancyCall(new PyObject[] {arg1, arg2, arg3, arg4}); case 30: - return fancyCall(new PyObject[]{arg1, arg2, arg3, arg4}); + return fancyCall(new PyObject[] {arg1, arg2, arg3, arg4}); case 31: - return fancyCall(new PyObject[]{arg1, arg2, arg3, arg4}); + return fancyCall(new PyObject[] {arg1, arg2, arg3, arg4}); case 43: - return fancyCall(new PyObject[]{arg1, arg2, arg3, arg4}); + return fancyCall(new PyObject[] {arg1, arg2, arg3, arg4}); default: throw info.unexpectedCall(4, false); } @@ -289,6 +306,8 @@ */ public class __builtin__ { + private static final PyStringMap internedStrings = new PyStringMap(); + public static void fillWithBuiltins(PyObject dict) { /* newstyle */ dict.__setitem__("object", PyObject.TYPE); @@ -304,7 +323,6 @@ dict.__setitem__("tuple", PyTuple.TYPE); dict.__setitem__("set", PySet.TYPE); dict.__setitem__("frozenset", PyFrozenSet.TYPE); - dict.__setitem__("property", PyProperty.TYPE); dict.__setitem__("staticmethod", PyStaticMethod.TYPE); dict.__setitem__("classmethod", PyClassMethod.TYPE); @@ -316,8 +334,6 @@ dict.__setitem__("slice", PySlice.TYPE); dict.__setitem__("xrange", PyXRange.TYPE); - /* - */ - dict.__setitem__("None", Py.None); dict.__setitem__("NotImplemented", Py.NotImplemented); dict.__setitem__("Ellipsis", Py.Ellipsis); @@ -394,10 +410,10 @@ public static PyObject apply(PyObject o, PyObject args, PyDictionary kws) { PyObject[] a; String[] kw; - Map table = kws.table; + Map<PyObject, PyObject> table = kws.table; if (table.size() > 0) { - Iterator ik = table.keySet().iterator(); - Iterator iv = table.values().iterator(); + Iterator<PyObject> ik = table.keySet().iterator(); + Iterator<PyObject> iv = table.values().iterator(); int n = table.size(); kw = new String[n]; PyObject[] aargs = Py.make_array(args); @@ -406,8 +422,12 @@ int offset = aargs.length; for (int i = 0; i < n; i++) { - kw[i] = ((PyString) ik.next()).internedString(); - a[i + offset] = (PyObject) iv.next(); + PyObject name = ik.next(); + if (name.getClass() != PyString.class) { + throw Py.TypeError(String.format("keywords must be strings")); + } + kw[i] = ((PyString)name).internedString(); + a[i + offset] = iv.next(); } return o.__call__(a, kw); } else { @@ -462,7 +482,8 @@ try { ret = (PyList) retObj; } catch (ClassCastException e) { - throw Py.TypeError("Expected keys() to be a list, not '" + retObj.getType().fastGetName() + "'"); + throw Py.TypeError(String.format("Expected keys() to be a list, not '%s'", + retObj.getType().fastGetName())); } ret.sort(); return ret; @@ -519,12 +540,13 @@ execfile_flags(name, globals, locals, Py.getCompilerFlags()); } - public static void execfile_flags(String name, PyObject globals, PyObject locals, CompilerFlags cflags) { + public static void execfile_flags(String name, PyObject globals, PyObject locals, + CompilerFlags cflags) { verify_mappings(globals, locals, true); - java.io.FileInputStream file; + FileInputStream file; try { - file = new java.io.FileInputStream(new RelativeFile(name)); - } catch (java.io.FileNotFoundException e) { + file = new FileInputStream(new RelativeFile(name)); + } catch (FileNotFoundException e) { throw Py.IOError(e); } PyCode code; @@ -534,7 +556,7 @@ } finally { try { file.close(); - } catch (java.io.IOException e) { + } catch (IOException e) { throw Py.IOError(e); } } @@ -694,7 +716,6 @@ public static PyObject input() { return input(new PyString("")); } - private static final PyStringMap internedStrings = new PyStringMap(); public static PyString intern(PyObject obj) { if (!(obj instanceof PyString) || obj instanceof PyUnicode) { @@ -705,11 +726,6 @@ throw Py.TypeError("can't intern subclass of string"); } PyString s = (PyString)obj; - - // XXX: for some reason, not seeing this as an instance of PyStringDerived when derived - if (s instanceof PyStringDerived) { - throw Py.TypeError("can't intern subclass of string"); - } String istring = s.internedString(); PyObject ret = internedStrings.__finditem__(istring); if (ret != null) { @@ -773,7 +789,8 @@ PyObject[] iters = new PyObject[n]; for (int j = 0; j < n; j++) { - iters[j] = Py.iter(argstar[j + 1], "argument " + (j + 1) + " to map() must support iteration"); + iters[j] = Py.iter(argstar[j + 1], "argument " + (j + 1) + + " to map() must support iteration"); } while (true) { @@ -821,7 +838,7 @@ } } throw Py.TypeError("ord() expected a character, but string of length " + - length + " found"); + length + " found"); } public static PyObject pow(PyObject x, PyObject y) { @@ -1068,7 +1085,7 @@ } public static PyObject reload(PySystemState o) { - // reinitialize methods + // reinitialize methods o.reload(); return o; } @@ -1123,7 +1140,11 @@ } } - public static PyString __doc__zip = new PyString("zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n" + "\n" + "Return a list of tuples, where each tuple contains the i-th element\n" + "from each of the argument sequences. The returned list is\n" + "truncated in length to the length of the shortest argument sequence."); + public static PyString __doc__zip = new PyString( + "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\n" + + "Return a list of tuples, where each tuple contains the i-th element\n" + + "from each of the argument sequences. The returned list is\n" + + "truncated in length to the length of the shortest argument sequence."); public static PyObject zip() { return new PyList(); @@ -1180,11 +1201,13 @@ return __import__(name, globals, locals, null, imp.DEFAULT_LEVEL); } - public static PyObject __import__(String name, PyObject globals, PyObject locals, PyObject fromlist) { + public static PyObject __import__(String name, PyObject globals, PyObject locals, + PyObject fromlist) { return __import__(name, globals, locals, fromlist, imp.DEFAULT_LEVEL); } - public static PyObject __import__(String name, PyObject globals, PyObject locals, PyObject fromlist, int level) { + public static PyObject __import__(String name, PyObject globals, PyObject locals, + PyObject fromlist, int level) { PyFrame frame = Py.getFrame(); PyObject builtins; if (frame != null && frame.f_builtins != null) { @@ -1198,7 +1221,8 @@ return null; } - PyObject module = __import__.__call__(new PyObject[]{Py.newString(name), globals, locals, fromlist, Py.newInteger(level)}); + PyObject module = __import__.__call__(new PyObject[] {Py.newString(name), globals, locals, + fromlist, Py.newInteger(level)}); return module; } } @@ -1222,14 +1246,15 @@ @Override public PyObject __call__(PyObject args[], String keywords[]) { ArgParser ap = new ArgParser("__import__", args, keywords, - new String[]{"name", "globals", "locals", "fromlist", "level"}, + new String[] {"name", "globals", "locals", "fromlist", + "level"}, 1); String module = ap.getString(0); PyObject globals = ap.getPyObject(1, null); PyObject fromlist = ap.getPyObject(3, Py.EmptyTuple); int level = ap.getInt(4, imp.DEFAULT_LEVEL); return imp.importName(module.intern(), fromlist == Py.None || fromlist.__len__() == 0, - globals, fromlist, level); + globals, fromlist, level); } } @@ -1241,13 +1266,15 @@ @Override public PyObject __call__(PyObject args[], String kwds[]) { if (args.length == 0) { - throw Py.TypeError(" sorted() takes at least 1 argument (0 given)"); + throw Py.TypeError("sorted() takes at least 1 argument (0 given)"); } else if (args.length > 4) { - throw Py.TypeError(" sorted() takes at most 4 arguments (" + args.length + " given)"); + throw Py.TypeError(String.format("sorted() takes at most 4 arguments (%s given)", + args.length)); } else { PyObject iter = args[0].__iter__(); if (iter == null) { - throw Py.TypeError("'" + args[0].getType().fastGetName() + "' object is not iterable"); + throw Py.TypeError(String.format("'%s' object is not iterable", + args[0].getType().fastGetName())); } } @@ -1255,8 +1282,8 @@ PyObject newargs[] = new PyObject[args.length - 1]; System.arraycopy(args, 1, newargs, 0, args.length - 1); - ArgParser ap = new ArgParser("sorted", newargs, kwds, new String[]{"cmp", "key", "reverse"}, 0); - + ArgParser ap = new ArgParser("sorted", newargs, kwds, + new String[] {"cmp", "key", "reverse"}, 0); PyObject cmp = ap.getPyObject(0, Py.None); PyObject key = ap.getPyObject(1, Py.None); PyObject reverse = ap.getPyObject(2, Py.None); @@ -1291,7 +1318,8 @@ class AnyFunction extends PyBuiltinFunctionNarrow { AnyFunction() { super("any", 1, 1, - "any(iterable) -> bool\n\nReturn True if bool(x) is True for any x in the iterable."); + "any(iterable) -> bool\n\n" + + "Return True if bool(x) is True for any x in the iterable."); } @Override @@ -1312,7 +1340,8 @@ class MaxFunction extends PyBuiltinFunction { MaxFunction() { super("max", - "max(iterable[, key=func]) -> value\nmax(a, b, c, ...[, key=func]) -> value\n\n" + + "max(iterable[, key=func]) -> value\n" + + "max(a, b, c, ...[, key=func]) -> value\n\n" + "With a single iterable argument, return its largest item.\n" + "With two or more arguments, return the largest argument."); } @@ -1331,16 +1360,14 @@ PyObject newargs[] = new PyObject[argslen - 1]; System.arraycopy(args, 0, newargs, 0, argslen - 1); args = newargs; - } - else { + } else { throw Py.TypeError("max() got an unexpected keyword argument"); } } if (args.length > 1) { return max(new PyTuple(args), key); - } - else { + } else { return max(args[0], key); } } @@ -1352,8 +1379,7 @@ PyObject itemKey; if (key == null) { itemKey = item; - } - else { + } else { itemKey = key.__call__(item); } if (maxKey == null || itemKey._gt(maxKey).__nonzero__()) { @@ -1372,7 +1398,8 @@ class MinFunction extends PyBuiltinFunction { MinFunction() { super("min", - "min(iterable[, key=func]) -> value\nmin(a, b, c, ...[, key=func]) -> value\n\n" + + "min(iterable[, key=func]) -> value\n" + + "min(a, b, c, ...[, key=func]) -> value\n\n" + "With a single iterable argument, return its smallest item.\n" + "With two or more arguments, return the smallest argument.'"); } @@ -1383,7 +1410,7 @@ PyObject key = null; if (args.length - kwds.length == 0) { - throw Py.TypeError(" min() expected 1 arguments, got 0"); + throw Py.TypeError("min() expected 1 arguments, got 0"); } if (kwds.length > 0) { if (kwds[0].equals("key")) { @@ -1391,16 +1418,14 @@ PyObject newargs[] = new PyObject[argslen - 1]; System.arraycopy(args, 0, newargs, 0, argslen - 1); args = newargs; - } - else { + } else { throw Py.TypeError("min() got an unexpected keyword argument"); } } if (args.length > 1) { return min(new PyTuple(args), key); - } - else { + } else { return min(args[0], key); } } @@ -1412,8 +1437,7 @@ PyObject itemKey; if (key == null) { itemKey = item; - } - else { + } else { itemKey = key.__call__(item); } if (minKey == null || itemKey._lt(minKey).__nonzero__()) { @@ -1500,19 +1524,19 @@ return compile(source, filename, kind, cflags, dont_inherit); } - public static PyObject compile(PyObject source, String filename, CompileMode kind, CompilerFlags cflags, - boolean dont_inherit) { + public static PyObject compile(PyObject source, String filename, CompileMode kind, + CompilerFlags cflags, boolean dont_inherit) { cflags = Py.getCompilerFlags(cflags, dont_inherit); - + mod ast = py2node(source); if (ast == null) { if (!(source instanceof PyString)) { throw Py.TypeError("expected a readable buffer object"); } cflags.source_is_utf8 = source instanceof PyUnicode; - + String data = source.toString(); - + if (data.contains("\0")) { throw Py.TypeError("compile() expected string without null bytes"); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-27 21:30:36
|
Revision: 6915 http://jython.svn.sourceforge.net/jython/?rev=6915&view=rev Author: fwierzbicki Date: 2009-10-27 21:30:30 +0000 (Tue, 27 Oct 2009) Log Message: ----------- yields member of CodeCompiler can now be private. Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-27 03:38:41 UTC (rev 6914) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-27 21:30:30 UTC (rev 6915) @@ -119,10 +119,8 @@ private String className; private Stack<Label> continueLabels, breakLabels; private Stack<ExceptionHandler> exceptionHandlers; + private Vector<Label> yields = new Vector<Label>(); - //Module uses this, otherwise I'd make it private. - Vector<Label> yields = new Vector<Label>(); - /* * break/continue finally's level. This is the lowest level in the * exceptionHandlers which should be executed at break or continue. It is This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-27 03:38:53
|
Revision: 6914 http://jython.svn.sourceforge.net/jython/?rev=6914&view=rev Author: fwierzbicki Date: 2009-10-27 03:38:41 +0000 (Tue, 27 Oct 2009) Log Message: ----------- refactor scope param use in parse method. Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-27 03:11:20 UTC (rev 6913) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-27 03:38:41 UTC (rev 6914) @@ -258,6 +258,8 @@ this.className = className; this.code = code; this.cflags = cflags; + this.my_scope = scope; + this.tbl = scope.tbl; //BEGIN preparse if (classBody) { @@ -273,16 +275,15 @@ } Label genswitch = new Label(); - if (scope.generator) { + if (my_scope.generator) { code.goto_(genswitch); } Label start = new Label(); code.label(start); - int nparamcell = scope.jy_paramcells.size(); + int nparamcell = my_scope.jy_paramcells.size(); if (nparamcell > 0) { - Map<String, SymInfo> tbl = scope.tbl; - java.util.List<String> paramcells = scope.jy_paramcells; + java.util.List<String> paramcells = my_scope.jy_paramcells; for (int i = 0; i < nparamcell; i++) { code.aload(1); SymInfo syminf = tbl.get(paramcells.get(i)); @@ -294,16 +295,13 @@ } //END preparse - my_scope = scope; + optimizeGlobals = checkOptimizeGlobals(fast_locals, my_scope); - tbl = scope.tbl; - optimizeGlobals = checkOptimizeGlobals(fast_locals, scope); - - if (scope.max_with_count > 0) { + if (my_scope.max_with_count > 0) { // allocate for all the with-exits we will have in the frame; // this allows yield and with to happily co-exist loadFrame(); - code.iconst(scope.max_with_count); + code.iconst(my_scope.max_with_count); code.anewarray(p(PyObject.class)); code.putfield(p(PyFrame.class), "f_exits", ci(PyObject[].class)); } @@ -326,7 +324,7 @@ //BEGIN postparse // similar to visitResume code in pyasm.py - if (scope.generator) { + if (my_scope.generator) { code.label(genswitch); code.aload(1); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-27 03:11:31
|
Revision: 6913 http://jython.svn.sourceforge.net/jython/?rev=6913&view=rev Author: pjenvey Date: 2009-10-27 03:11:20 +0000 (Tue, 27 Oct 2009) Log Message: ----------- != None -> is not None Modified Paths: -------------- trunk/jython/Lib/socket.py Modified: trunk/jython/Lib/socket.py =================================================================== --- trunk/jython/Lib/socket.py 2009-10-27 03:00:16 UTC (rev 6912) +++ trunk/jython/Lib/socket.py 2009-10-27 03:11:20 UTC (rev 6913) @@ -388,7 +388,7 @@ def accept(self): if self.mode in (MODE_BLOCKING, MODE_NONBLOCKING): new_cli_chan = self.jchannel.accept() - if new_cli_chan != None: + if new_cli_chan is not None: return _client_socket_impl(new_cli_chan.socket()) else: return None This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-27 03:00:27
|
Revision: 6912 http://jython.svn.sourceforge.net/jython/?rev=6912&view=rev Author: fwierzbicki Date: 2009-10-27 03:00:16 +0000 (Tue, 27 Oct 2009) Log Message: ----------- Code from Module reaching into internals of CodeCompiler moved to CodeCompiler Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/compiler/Module.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-27 02:56:41 UTC (rev 6911) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-27 03:00:16 UTC (rev 6912) @@ -259,6 +259,41 @@ this.code = code; this.cflags = cflags; + //BEGIN preparse + if (classBody) { + // Set the class's __module__ to __name__. fails when there's no __name__ + code.aload(1); + code.ldc("__module__"); + + code.aload(1); + code.ldc("__name__"); + code.invokevirtual(p(PyFrame.class), "getname", sig(PyObject.class, String.class)); + code.invokevirtual(p(PyFrame.class), "setlocal", sig(Void.TYPE, String.class, + PyObject.class)); + } + + Label genswitch = new Label(); + if (scope.generator) { + code.goto_(genswitch); + } + Label start = new Label(); + code.label(start); + + int nparamcell = scope.jy_paramcells.size(); + if (nparamcell > 0) { + Map<String, SymInfo> tbl = scope.tbl; + java.util.List<String> paramcells = scope.jy_paramcells; + for (int i = 0; i < nparamcell; i++) { + code.aload(1); + SymInfo syminf = tbl.get(paramcells.get(i)); + code.iconst(syminf.locals_index); + code.iconst(syminf.env_index); + code.invokevirtual(p(PyFrame.class), "to_cell", sig(Void.TYPE, Integer.TYPE, + Integer.TYPE)); + } + } + //END preparse + my_scope = scope; tbl = scope.tbl; @@ -287,6 +322,24 @@ code.areturn(); } } + + //BEGIN postparse + + // similar to visitResume code in pyasm.py + if (scope.generator) { + code.label(genswitch); + + code.aload(1); + code.getfield(p(PyFrame.class), "f_lasti", "I"); + Label[] y = new Label[yields.size() + 1]; + + y[0] = start; + for (int i = 1; i < y.length; i++) { + y[i] = yields.get(i - 1); + } + code.tableswitch(0, y.length - 1, start, y); + } + //END postparse } @Override Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2009-10-27 02:56:41 UTC (rev 6911) +++ trunk/jython/src/org/python/compiler/Module.java 2009-10-27 03:00:16 UTC (rev 6912) @@ -507,55 +507,7 @@ sig(PyObject.class, PyFrame.class, ThreadState.class), ACC_PUBLIC); - if (classBody) { - // Set the class's __module__ to __name__. fails when there's no __name__ - c.aload(1); - c.ldc("__module__"); - - c.aload(1); - c.ldc("__name__"); - c.invokevirtual(p(PyFrame.class), "getname", sig(PyObject.class, String.class)); - c.invokevirtual(p(PyFrame.class), "setlocal", sig(Void.TYPE, String.class, - PyObject.class)); - } - - Label genswitch = new Label(); - if (scope.generator) { - c.goto_(genswitch); - } - Label start = new Label(); - c.label(start); - - int nparamcell = scope.jy_paramcells.size(); - if (nparamcell > 0) { - Map<String, SymInfo> tbl = scope.tbl; - List<String> paramcells = scope.jy_paramcells; - for (int i = 0; i < nparamcell; i++) { - c.aload(1); - SymInfo syminf = tbl.get(paramcells.get(i)); - c.iconst(syminf.locals_index); - c.iconst(syminf.env_index); - c.invokevirtual(p(PyFrame.class), "to_cell", sig(Void.TYPE, Integer.TYPE, - Integer.TYPE)); - } - } - compiler.parse(tree, c, fast_locals, className, classBody, scope, cflags); - // similar to visitResume code in pyasm.py - if (scope.generator) { - c.label(genswitch); - - c.aload(1); - c.getfield(p(PyFrame.class), "f_lasti", "I"); - Label[] yields = new Label[compiler.yields.size() + 1]; - - yields[0] = start; - for (int i = 1; i < yields.length; i++) { - yields[i] = compiler.yields.get(i - 1); - } - c.tableswitch(0, yields.length - 1, start, yields); - } - return code; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-27 02:56:47
|
Revision: 6911 http://jython.svn.sourceforge.net/jython/?rev=6911&view=rev Author: pjenvey Date: 2009-10-27 02:56:41 +0000 (Tue, 27 Oct 2009) Log Message: ----------- er, don't intern twice Modified Paths: -------------- trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2009-10-27 02:54:10 UTC (rev 6910) +++ trunk/jython/src/org/python/core/__builtin__.java 2009-10-27 02:56:41 UTC (rev 6911) @@ -640,7 +640,7 @@ throw Py.TypeError("getattr(): attribute name must be string"); } - PyObject result = obj.__findattr__(nameStr.intern()); + PyObject result = obj.__findattr__(nameStr); if (result != null) { return result; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-27 02:54:29
|
Revision: 6910 http://jython.svn.sourceforge.net/jython/?rev=6910&view=rev Author: pjenvey Date: 2009-10-27 02:54:10 +0000 (Tue, 27 Oct 2009) Log Message: ----------- speedup get/hasattr, use __findattr__ and intern the PyString itself, that way we don't have to do it again later if called with the same string Modified Paths: -------------- trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2009-10-26 21:15:12 UTC (rev 6909) +++ trunk/jython/src/org/python/core/__builtin__.java 2009-10-27 02:54:10 UTC (rev 6910) @@ -633,24 +633,23 @@ public static PyObject getattr(PyObject obj, PyObject name, PyObject def) { String nameStr; if (name instanceof PyUnicode) { - nameStr = ((PyUnicode)name).encode(); + nameStr = ((PyUnicode)name).encode().intern(); } else if (name instanceof PyString) { - nameStr = name.asString(); + nameStr = ((PyString)name).internedString(); } else { throw Py.TypeError("getattr(): attribute name must be string"); } - PyObject result; - try { - result = obj.__getattr__(nameStr.intern()); - } catch (PyException pye) { - if (pye.match(Py.AttributeError) && def != null) { - result = def; - } else { - throw pye; - } + PyObject result = obj.__findattr__(nameStr.intern()); + if (result != null) { + return result; } - return result; + if (def != null) { + return def; + } + // throws AttributeError + obj.noAttributeError(nameStr); + return null; } public static PyObject globals() { @@ -662,13 +661,13 @@ if (name instanceof PyUnicode) { nameStr = ((PyUnicode)name).encode().intern(); } else if (name instanceof PyString) { - nameStr = name.asString(); + nameStr = ((PyString)name).internedString(); } else { throw Py.TypeError("hasattr(): attribute name must be string"); } try { - return obj.__findattr__(nameStr.intern()) != null; + return obj.__findattr__(nameStr) != null; } catch (PyException pye) { // swallow } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-26 21:15:18
|
Revision: 6909 http://jython.svn.sourceforge.net/jython/?rev=6909&view=rev Author: pjenvey Date: 2009-10-26 21:15:12 +0000 (Mon, 26 Oct 2009) Log Message: ----------- PyBoolean can just inherit various things from PyInteger, cleanup Modified Paths: -------------- trunk/jython/src/org/python/core/PyBoolean.java Modified: trunk/jython/src/org/python/core/PyBoolean.java =================================================================== --- trunk/jython/src/org/python/core/PyBoolean.java 2009-10-26 21:05:42 UTC (rev 6908) +++ trunk/jython/src/org/python/core/PyBoolean.java 2009-10-26 21:15:12 UTC (rev 6909) @@ -1,3 +1,4 @@ +/* Copyright (c) Jython Developers */ package org.python.core; import org.python.expose.ExposedMethod; @@ -6,13 +7,20 @@ import org.python.expose.MethodType; /** - * A builtin python bool. + * The builtin python bool. */ @ExposedType(name = "bool", isBaseType = false, doc = BuiltinDocs.bool_doc) public class PyBoolean extends PyInteger { - + public static final PyType TYPE = PyType.fromClass(PyBoolean.class); - + + private boolean value; + + public PyBoolean(boolean value) { + super(TYPE, value ? 1 : 0); + this.value = value; + } + @ExposedNew public static PyObject bool_new(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { @@ -23,18 +31,8 @@ } return obj.__nonzero__() ? Py.True : Py.False; } - - private boolean value; - public PyBoolean(boolean value) { - super(TYPE, value ? 1 : 0); - this.value = value; - } - - public int getValue() { - return value ? 1 : 0; - } - + @Override public String toString() { return bool_toString(); } @@ -44,6 +42,7 @@ return value ? "True" : "False"; } + @Override public int hashCode() { return bool___hash__(); } @@ -53,6 +52,7 @@ return value ? 1 : 0; } + @Override public boolean __nonzero__() { return bool___nonzero__(); } @@ -62,28 +62,33 @@ return value; } - public Object __tojava__(Class c) { - if (c == Boolean.TYPE || c == Boolean.class || - c == Object.class ) { + @Override + public Object __tojava__(Class<?> c) { + if (c == Boolean.TYPE || c == Boolean.class || c == Object.class ) { return Boolean.valueOf(value); } - if (c == Integer.TYPE || c == Number.class || - c == Integer.class) { + if (c == Integer.TYPE || c == Number.class || c == Integer.class) { return Integer.valueOf(value ? 1 : 0); } - if (c == Byte.TYPE || c == Byte.class) + if (c == Byte.TYPE || c == Byte.class) { return Byte.valueOf((byte)(value ? 1 : 0)); - if (c == Short.TYPE || c == Short.class) + } + if (c == Short.TYPE || c == Short.class) { return Short.valueOf((short)(value ? 1 : 0)); - if (c == Long.TYPE || c == Long.class) + } + if (c == Long.TYPE || c == Long.class) { return Long.valueOf(value ? 1 : 0); - if (c == Float.TYPE || c == Float.class) + } + if (c == Float.TYPE || c == Float.class) { return Float.valueOf(value ? 1 : 0); - if (c == Double.TYPE || c == Double.class) + } + if (c == Double.TYPE || c == Double.class) { return Double.valueOf(value ? 1 : 0); + } return super.__tojava__(c); } + @Override public PyObject __and__(PyObject right) { return bool___and__(right); } @@ -93,12 +98,13 @@ if (right instanceof PyBoolean) { return Py.newBoolean(value & ((PyBoolean)right).value); } else if (right instanceof PyInteger) { - return Py.newInteger(getValue() & ((PyInteger)right).getValue()); + return Py.newInteger(getValue() & ((PyInteger)right).getValue()); } else { return null; } } + @Override public PyObject __xor__(PyObject right) { return bool___xor__(right); } @@ -108,27 +114,29 @@ if (right instanceof PyBoolean) { return Py.newBoolean(value ^ ((PyBoolean)right).value); } else if (right instanceof PyInteger) { - return Py.newInteger(getValue() ^ ((PyInteger)right).getValue()); + return Py.newInteger(getValue() ^ ((PyInteger)right).getValue()); } else { return null; } } + @Override public PyObject __or__(PyObject right) { return bool___or__(right); } - + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bool___or___doc) final PyObject bool___or__(PyObject right) { if (right instanceof PyBoolean) { return Py.newBoolean(value | ((PyBoolean)right).value); } else if (right instanceof PyInteger) { - return Py.newInteger(getValue() | ((PyInteger)right).getValue()); + return Py.newInteger(getValue() | ((PyInteger)right).getValue()); } else { return null; } } + @Override public PyObject __neg__() { return bool___neg__(); } @@ -138,6 +146,7 @@ return Py.newInteger(value ? -1 : 0); } + @Override public PyObject __pos__() { return bool___pos__(); } @@ -147,6 +156,7 @@ return Py.newInteger(value ? 1 : 0); } + @Override public PyObject __abs__() { return bool___abs__(); } @@ -155,18 +165,4 @@ final PyObject bool___abs__() { return Py.newInteger(value ? 1 : 0); } - - public long asLong(int index) { - return value ? 1 : 0; - } - - public int asInt(int index) { - return value ? 1 : 0; - } - - @Override - public int asInt() { - return value ? 1 : 0; - } - } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-26 21:06:05
|
Revision: 6908 http://jython.svn.sourceforge.net/jython/?rev=6908&view=rev Author: pjenvey Date: 2009-10-26 21:05:42 +0000 (Mon, 26 Oct 2009) Log Message: ----------- bool/slice aren't base types, they dont need Deriveds Modified Paths: -------------- trunk/jython/src/org/python/core/PyBoolean.java trunk/jython/src/org/python/core/PySlice.java trunk/jython/src/templates/mappings Removed Paths: ------------- trunk/jython/src/org/python/core/PyBooleanDerived.java trunk/jython/src/org/python/core/PySliceDerived.java trunk/jython/src/templates/bool.derived trunk/jython/src/templates/slice.derived Modified: trunk/jython/src/org/python/core/PyBoolean.java =================================================================== --- trunk/jython/src/org/python/core/PyBoolean.java 2009-10-26 20:11:44 UTC (rev 6907) +++ trunk/jython/src/org/python/core/PyBoolean.java 2009-10-26 21:05:42 UTC (rev 6908) @@ -14,34 +14,23 @@ public static final PyType TYPE = PyType.fromClass(PyBoolean.class); @ExposedNew - public static PyObject bool_new(PyNewWrapper new_, - boolean init, - PyType subtype, - PyObject[] args, - String[] keywords) { + public static PyObject bool_new(PyNewWrapper new_, boolean init, PyType subtype, + PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("bool", args, keywords, new String[] {"x"}, 0); - PyObject x = ap.getPyObject(0, null); - if (x == null) { + PyObject obj = ap.getPyObject(0, null); + if (obj == null) { return Py.False; } - if (new_.for_type == subtype) { - return x.__nonzero__() ? Py.True : Py.False; - } else { - return new PyBooleanDerived(subtype, x.__nonzero__()); - } + return obj.__nonzero__() ? Py.True : Py.False; } private boolean value; - public PyBoolean(PyType subType, boolean v) { - super(subType, v ? 1 : 0); - value = v; + public PyBoolean(boolean value) { + super(TYPE, value ? 1 : 0); + this.value = value; } - public PyBoolean(boolean v) { - this(TYPE, v); - } - public int getValue() { return value ? 1 : 0; } Deleted: trunk/jython/src/org/python/core/PyBooleanDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyBooleanDerived.java 2009-10-26 20:11:44 UTC (rev 6907) +++ trunk/jython/src/org/python/core/PyBooleanDerived.java 2009-10-26 21:05:42 UTC (rev 6908) @@ -1,1116 +0,0 @@ -/* Generated file, do not modify. See jython/src/templates/gderived.py. */ -package org.python.core; - -import java.io.Serializable; - -public class PyBooleanDerived extends PyBoolean implements Slotted { - - public PyObject getSlot(int index) { - return slots[index]; - } - - public void setSlot(int index,PyObject value) { - slots[index]=value; - } - - private PyObject[]slots; - - private PyObject dict; - - public PyObject fastGetDict() { - return dict; - } - - public PyObject getDict() { - return dict; - } - - public void setDict(PyObject newDict) { - if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { - dict=newDict; - } else { - throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); - } - } - - public void delDict() { - // deleting an object's instance dict makes it grow a new one - dict=new PyStringMap(); - } - - public PyBooleanDerived(PyType subtype,boolean v) { - super(subtype,v); - slots=new PyObject[subtype.getNumSlots()]; - dict=subtype.instDict(); - } - - public PyString __str__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__str__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyString) - return(PyString)res; - throw Py.TypeError("__str__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); - } - return super.__str__(); - } - - public PyString __repr__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__repr__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyString) - return(PyString)res; - throw Py.TypeError("__repr__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); - } - return super.__repr__(); - } - - public PyString __hex__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__hex__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyString) - return(PyString)res; - throw Py.TypeError("__hex__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); - } - return super.__hex__(); - } - - public PyString __oct__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__oct__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyString) - return(PyString)res; - throw Py.TypeError("__oct__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); - } - return super.__oct__(); - } - - public PyFloat __float__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__float__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyFloat) - return(PyFloat)res; - throw Py.TypeError("__float__"+" returned non-"+"float"+" (type "+res.getType().fastGetName()+")"); - } - return super.__float__(); - } - - public PyComplex __complex__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__complex__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyComplex) - return(PyComplex)res; - throw Py.TypeError("__complex__"+" returned non-"+"complex"+" (type "+res.getType().fastGetName()+")"); - } - return super.__complex__(); - } - - public PyObject __pos__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__pos__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(); - return super.__pos__(); - } - - public PyObject __neg__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__neg__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(); - return super.__neg__(); - } - - public PyObject __abs__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__abs__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(); - return super.__abs__(); - } - - public PyObject __invert__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__invert__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(); - return super.__invert__(); - } - - public PyObject __reduce__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__reduce__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(); - return super.__reduce__(); - } - - public PyObject __add__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__add__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__add__(other); - } - - public PyObject __radd__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__radd__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__radd__(other); - } - - public PyObject __sub__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__sub__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__sub__(other); - } - - public PyObject __rsub__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rsub__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rsub__(other); - } - - public PyObject __mul__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__mul__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__mul__(other); - } - - public PyObject __rmul__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rmul__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rmul__(other); - } - - public PyObject __div__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__div__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__div__(other); - } - - public PyObject __rdiv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rdiv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rdiv__(other); - } - - public PyObject __floordiv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__floordiv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__floordiv__(other); - } - - public PyObject __rfloordiv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rfloordiv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rfloordiv__(other); - } - - public PyObject __truediv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__truediv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__truediv__(other); - } - - public PyObject __rtruediv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rtruediv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rtruediv__(other); - } - - public PyObject __mod__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__mod__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__mod__(other); - } - - public PyObject __rmod__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rmod__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rmod__(other); - } - - public PyObject __divmod__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__divmod__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__divmod__(other); - } - - public PyObject __rdivmod__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rdivmod__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rdivmod__(other); - } - - public PyObject __rpow__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rpow__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rpow__(other); - } - - public PyObject __lshift__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__lshift__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__lshift__(other); - } - - public PyObject __rlshift__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rlshift__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rlshift__(other); - } - - public PyObject __rshift__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rshift__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rshift__(other); - } - - public PyObject __rrshift__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rrshift__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rrshift__(other); - } - - public PyObject __and__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__and__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__and__(other); - } - - public PyObject __rand__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rand__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rand__(other); - } - - public PyObject __or__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__or__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__or__(other); - } - - public PyObject __ror__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__ror__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__ror__(other); - } - - public PyObject __xor__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__xor__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__xor__(other); - } - - public PyObject __rxor__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rxor__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rxor__(other); - } - - public PyObject __lt__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__lt__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__lt__(other); - } - - public PyObject __le__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__le__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__le__(other); - } - - public PyObject __gt__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__gt__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__gt__(other); - } - - public PyObject __ge__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__ge__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__ge__(other); - } - - public PyObject __eq__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__eq__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__eq__(other); - } - - public PyObject __ne__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__ne__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__ne__(other); - } - - public PyObject __iadd__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__iadd__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__iadd__(other); - } - - public PyObject __isub__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__isub__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__isub__(other); - } - - public PyObject __imul__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__imul__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__imul__(other); - } - - public PyObject __idiv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__idiv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__idiv__(other); - } - - public PyObject __ifloordiv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__ifloordiv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__ifloordiv__(other); - } - - public PyObject __itruediv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__itruediv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__itruediv__(other); - } - - public PyObject __imod__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__imod__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__imod__(other); - } - - public PyObject __ipow__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__ipow__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__ipow__(other); - } - - public PyObject __ilshift__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__ilshift__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__ilshift__(other); - } - - public PyObject __irshift__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__irshift__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__irshift__(other); - } - - public PyObject __iand__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__iand__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__iand__(other); - } - - public PyObject __ior__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__ior__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__ior__(other); - } - - public PyObject __ixor__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__ixor__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__ixor__(other); - } - - public PyObject __int__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__int__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyInteger||res instanceof PyLong) - return res; - throw Py.TypeError("__int__"+" should return an integer"); - } - return super.__int__(); - } - - public PyObject __long__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__long__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyLong||res instanceof PyInteger) - return res; - throw Py.TypeError("__long__"+" returned non-"+"long"+" (type "+res.getType().fastGetName()+")"); - } - return super.__long__(); - } - - public int hashCode() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__hash__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyInteger) { - return((PyInteger)res).getValue(); - } else - if (res instanceof PyLong) { - return((PyLong)res).getValue().intValue(); - } - throw Py.TypeError("__hash__ should return a int"); - } - if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); - } - return super.hashCode(); - } - - public PyUnicode __unicode__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__unicode__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyUnicode) - return(PyUnicode)res; - if (res instanceof PyString) - return new PyUnicode((PyString)res); - throw Py.TypeError("__unicode__"+" should return a "+"unicode"); - } - return super.__unicode__(); - } - - public int __cmp__(PyObject other) { - PyType self_type=getType(); - PyObject[]where_type=new PyObject[1]; - PyObject impl=self_type.lookup_where("__cmp__",where_type); - // Full Compatibility with CPython __cmp__: - // If the derived type don't override __cmp__, the - // *internal* super().__cmp__ should be called, not the - // exposed one. The difference is that the exposed __cmp__ - // throws a TypeError if the argument is an instance of the same type. - if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { - return super.__cmp__(other); - } - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) { - return-2; - } - int c=res.asInt(); - return c<0?-1:c>0?1:0; - } - - public boolean __nonzero__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__nonzero__"); - if (impl==null) { - impl=self_type.lookup("__len__"); - if (impl==null) - return super.__nonzero__(); - } - PyObject o=impl.__get__(this,self_type).__call__(); - Class c=o.getClass(); - if (c!=PyInteger.class&&c!=PyBoolean.class) { - throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); - } - return o.__nonzero__(); - } - - public boolean __contains__(PyObject o) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__contains__"); - if (impl==null) - return super.__contains__(o); - return impl.__get__(this,self_type).__call__(o).__nonzero__(); - } - - public int __len__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__len__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyInteger) - return((PyInteger)res).getValue(); - throw Py.TypeError("__len__ should return a int"); - } - return super.__len__(); - } - - public PyObject __iter__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__iter__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(); - impl=self_type.lookup("__getitem__"); - if (impl==null) - return super.__iter__(); - return new PySequenceIter(this); - } - - public PyObject __iternext__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("next"); - if (impl!=null) { - try { - return impl.__get__(this,self_type).__call__(); - } catch (PyException exc) { - if (exc.match(Py.StopIteration)) - return null; - throw exc; - } - } - return super.__iternext__(); // ??? - } - - public PyObject __finditem__(PyObject key) { // ??? - PyType self_type=getType(); - PyObject impl=self_type.lookup("__getitem__"); - if (impl!=null) - try { - return impl.__get__(this,self_type).__call__(key); - } catch (PyException exc) { - if (exc.match(Py.LookupError)) - return null; - throw exc; - } - return super.__finditem__(key); - } - - public PyObject __finditem__(int key) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__getitem__"); - if (impl!=null) - try { - return impl.__get__(this,self_type).__call__(new PyInteger(key)); - } catch (PyException exc) { - if (exc.match(Py.LookupError)) - return null; - throw exc; - } - return super.__finditem__(key); - } - - public PyObject __getitem__(PyObject key) { - // Same as __finditem__, without swallowing LookupErrors. This allows - // __getitem__ implementations written in Python to raise custom - // exceptions (such as subclasses of KeyError). - // - // We are forced to duplicate the code, instead of defining __finditem__ - // in terms of __getitem__. That's because PyObject defines __getitem__ - // in terms of __finditem__. Therefore, we would end with an infinite - // loop when self_type.lookup("__getitem__") returns null: - // - // __getitem__ -> super.__getitem__ -> __finditem__ -> __getitem__ - // - // By duplicating the (short) lookup and call code, we are safe, because - // the call chains will be: - // - // __finditem__ -> super.__finditem__ - // - // __getitem__ -> super.__getitem__ -> __finditem__ -> super.__finditem__ - - PyType self_type=getType(); - PyObject impl=self_type.lookup("__getitem__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(key); - return super.__getitem__(key); - } - - public void __setitem__(PyObject key,PyObject value) { // ??? - PyType self_type=getType(); - PyObject impl=self_type.lookup("__setitem__"); - if (impl!=null) { - impl.__get__(this,self_type).__call__(key,value); - return; - } - super.__setitem__(key,value); - } - - public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? - if (step!=null) { - return __getitem__(new PySlice(start,stop,step)); - } - PyType self_type=getType(); - PyObject impl=self_type.lookup("__getslice__"); - if (impl!=null) { - PyObject[]indices=PySlice.indices2(this,start,stop); - return impl.__get__(this,self_type).__call__(indices[0],indices[1]); - } - return super.__getslice__(start,stop,step); - } - - public void __setslice__(PyObject start,PyObject stop,PyObject step,PyObject value) { - if (step!=null) { - __setitem__(new PySlice(start,stop,step),value); - return; - } - PyType self_type=getType(); - PyObject impl=self_type.lookup("__setslice__"); - if (impl!=null) { - PyObject[]indices=PySlice.indices2(this,start,stop); - impl.__get__(this,self_type).__call__(indices[0],indices[1],value); - return; - } - super.__setslice__(start,stop,step,value); - } - - public void __delslice__(PyObject start,PyObject stop,PyObject step) { - if (step!=null) { - __delitem__(new PySlice(start,stop,step)); - return; - } - PyType self_type=getType(); - PyObject impl=self_type.lookup("__delslice__"); - if (impl!=null) { - PyObject[]indices=PySlice.indices2(this,start,stop); - impl.__get__(this,self_type).__call__(indices[0],indices[1]); - return; - } - super.__delslice__(start,stop,step); - } - - public void __delitem__(PyObject key) { // ??? - PyType self_type=getType(); - PyObject impl=self_type.lookup("__delitem__"); - if (impl!=null) { - impl.__get__(this,self_type).__call__(key); - return; - } - super.__delitem__(key); - } - - public PyObject __call__(PyObject args[],String keywords[]) { - ThreadState ts=Py.getThreadState(); - if (ts.recursion_depth++>ts.systemState.getrecursionlimit()) - throw Py.RuntimeError("maximum __call__ recursion depth exceeded"); - try { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__call__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(args,keywords); - return super.__call__(args,keywords); - } finally { - --ts.recursion_depth; - } - } - - public PyObject __findattr_ex__(String name) { - return Deriveds.__findattr_ex__(this,name); - } - - public void __setattr__(String name,PyObject value) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__setattr__"); - if (impl!=null) { - impl.__get__(this,self_type).__call__(PyString.fromInterned(name),value); - return; - } - super.__setattr__(name,value); - } - - public void __delattr__(String name) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__delattr__"); - if (impl!=null) { - impl.__get__(this,self_type).__call__(PyString.fromInterned(name)); - return; - } - super.__delattr__(name); - } - - public PyObject __get__(PyObject obj,PyObject type) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__get__"); - if (impl!=null) { - if (obj==null) - obj=Py.None; - if (type==null) - type=Py.None; - return impl.__get__(this,self_type).__call__(obj,type); - } - return super.__get__(obj,type); - } - - public void __set__(PyObject obj,PyObject value) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__set__"); - if (impl!=null) { - impl.__get__(this,self_type).__call__(obj,value); - return; - } - super.__set__(obj,value); - } - - public void __delete__(PyObject obj) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__delete__"); - if (impl!=null) { - impl.__get__(this,self_type).__call__(obj); - return; - } - super.__delete__(obj); - } - - public PyObject __pow__(PyObject other,PyObject modulo) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__pow__"); - if (impl!=null) { - PyObject res; - if (modulo==null) { - res=impl.__get__(this,self_type).__call__(other); - } else { - res=impl.__get__(this,self_type).__call__(other,modulo); - } - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__pow__(other,modulo); - } - - public void dispatch__init__(PyObject[]args,String[]keywords) { - Deriveds.dispatch__init__(this,args,keywords); - } - - public PyObject __index__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__index__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyInteger||res instanceof PyLong) { - return res; - } - throw Py.TypeError(String.format("__index__ returned non-(int,long) (type %s)",res.getType().fastGetName())); - } - return super.__index__(); - } - - public Object __tojava__(Class c) { - // If we are not being asked by the "default" conversion to java, then - // we can provide this as the result, as long as it is a instance of the - // specified class. Without this, derived.__tojava__(PyObject.class) - // would broke. (And that's not pure speculation: PyReflectedFunction's - // ReflectedArgs asks for things like that). - if ((c!=Object.class)&&(c!=Serializable.class)&&(c.isInstance(this))) { - return this; - } - // Otherwise, we call the derived __tojava__, if it exists: - PyType self_type=getType(); - PyObject impl=self_type.lookup("__tojava__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(Py.java2py(c)).__tojava__(Object.class); - return super.__tojava__(c); - } - - public Object __coerce_ex__(PyObject o) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__coerce__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(o); - if (res==Py.NotImplemented) - return Py.None; - if (!(res instanceof PyTuple)) - throw Py.TypeError("__coerce__ didn't return a 2-tuple"); - return((PyTuple)res).getArray(); - } - return super.__coerce_ex__(o); - } - - public String toString() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__repr__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (!(res instanceof PyString)) - throw Py.TypeError("__repr__ returned non-string (type "+res.getType().fastGetName()+")"); - return((PyString)res).toString(); - } - return super.toString(); - } - -} Modified: trunk/jython/src/org/python/core/PySlice.java =================================================================== --- trunk/jython/src/org/python/core/PySlice.java 2009-10-26 20:11:44 UTC (rev 6907) +++ trunk/jython/src/org/python/core/PySlice.java 2009-10-26 21:05:42 UTC (rev 6908) @@ -24,15 +24,11 @@ public PyObject step = Py.None; public PySlice() { - this(TYPE); + super(TYPE); } - public PySlice(PyType type) { - super(type); - } - public PySlice(PyObject start, PyObject stop, PyObject step) { - this(TYPE); + super(TYPE); if (start != null) { this.start = start; } @@ -45,24 +41,26 @@ } @ExposedNew - @ExposedMethod - final void slice___init__(PyObject[] args, String[] keywords) { + static PyObject slice_new(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, + String[] keywords) { if (args.length == 0) { throw Py.TypeError("slice expected at least 1 arguments, got " + args.length); } else if (args.length > 3) { throw Py.TypeError("slice expected at most 3 arguments, got " + args.length); } ArgParser ap = new ArgParser("slice", args, keywords, "start", "stop", "step"); + PySlice slice = new PySlice(); if (args.length == 1) { - stop = ap.getPyObject(0); + slice.stop = ap.getPyObject(0); } else if (args.length == 2) { - start = ap.getPyObject(0); - stop = ap.getPyObject(1); + slice.start = ap.getPyObject(0); + slice.stop = ap.getPyObject(1); } else if (args.length == 3) { - start = ap.getPyObject(0); - stop = ap.getPyObject(1); - step = ap.getPyObject(2); + slice.start = ap.getPyObject(0); + slice.stop = ap.getPyObject(1); + slice.step = ap.getPyObject(2); } + return slice; } @Override Deleted: trunk/jython/src/org/python/core/PySliceDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySliceDerived.java 2009-10-26 20:11:44 UTC (rev 6907) +++ trunk/jython/src/org/python/core/PySliceDerived.java 2009-10-26 21:05:42 UTC (rev 6908) @@ -1,1116 +0,0 @@ -/* Generated file, do not modify. See jython/src/templates/gderived.py. */ -package org.python.core; - -import java.io.Serializable; - -public class PySliceDerived extends PySlice implements Slotted { - - public PyObject getSlot(int index) { - return slots[index]; - } - - public void setSlot(int index,PyObject value) { - slots[index]=value; - } - - private PyObject[]slots; - - private PyObject dict; - - public PyObject fastGetDict() { - return dict; - } - - public PyObject getDict() { - return dict; - } - - public void setDict(PyObject newDict) { - if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { - dict=newDict; - } else { - throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); - } - } - - public void delDict() { - // deleting an object's instance dict makes it grow a new one - dict=new PyStringMap(); - } - - public PySliceDerived(PyType subtype) { - super(subtype); - slots=new PyObject[subtype.getNumSlots()]; - dict=subtype.instDict(); - } - - public PyString __str__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__str__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyString) - return(PyString)res; - throw Py.TypeError("__str__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); - } - return super.__str__(); - } - - public PyString __repr__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__repr__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyString) - return(PyString)res; - throw Py.TypeError("__repr__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); - } - return super.__repr__(); - } - - public PyString __hex__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__hex__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyString) - return(PyString)res; - throw Py.TypeError("__hex__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); - } - return super.__hex__(); - } - - public PyString __oct__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__oct__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyString) - return(PyString)res; - throw Py.TypeError("__oct__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); - } - return super.__oct__(); - } - - public PyFloat __float__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__float__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyFloat) - return(PyFloat)res; - throw Py.TypeError("__float__"+" returned non-"+"float"+" (type "+res.getType().fastGetName()+")"); - } - return super.__float__(); - } - - public PyComplex __complex__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__complex__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyComplex) - return(PyComplex)res; - throw Py.TypeError("__complex__"+" returned non-"+"complex"+" (type "+res.getType().fastGetName()+")"); - } - return super.__complex__(); - } - - public PyObject __pos__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__pos__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(); - return super.__pos__(); - } - - public PyObject __neg__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__neg__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(); - return super.__neg__(); - } - - public PyObject __abs__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__abs__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(); - return super.__abs__(); - } - - public PyObject __invert__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__invert__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(); - return super.__invert__(); - } - - public PyObject __reduce__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__reduce__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(); - return super.__reduce__(); - } - - public PyObject __add__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__add__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__add__(other); - } - - public PyObject __radd__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__radd__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__radd__(other); - } - - public PyObject __sub__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__sub__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__sub__(other); - } - - public PyObject __rsub__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rsub__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rsub__(other); - } - - public PyObject __mul__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__mul__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__mul__(other); - } - - public PyObject __rmul__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rmul__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rmul__(other); - } - - public PyObject __div__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__div__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__div__(other); - } - - public PyObject __rdiv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rdiv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rdiv__(other); - } - - public PyObject __floordiv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__floordiv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__floordiv__(other); - } - - public PyObject __rfloordiv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rfloordiv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rfloordiv__(other); - } - - public PyObject __truediv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__truediv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__truediv__(other); - } - - public PyObject __rtruediv__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rtruediv__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rtruediv__(other); - } - - public PyObject __mod__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__mod__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__mod__(other); - } - - public PyObject __rmod__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rmod__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rmod__(other); - } - - public PyObject __divmod__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__divmod__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__divmod__(other); - } - - public PyObject __rdivmod__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rdivmod__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rdivmod__(other); - } - - public PyObject __rpow__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rpow__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rpow__(other); - } - - public PyObject __lshift__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__lshift__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__lshift__(other); - } - - public PyObject __rlshift__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rlshift__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rlshift__(other); - } - - public PyObject __rshift__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rshift__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rshift__(other); - } - - public PyObject __rrshift__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rrshift__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rrshift__(other); - } - - public PyObject __and__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__and__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__and__(other); - } - - public PyObject __rand__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rand__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rand__(other); - } - - public PyObject __or__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__or__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__or__(other); - } - - public PyObject __ror__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__ror__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__ror__(other); - } - - public PyObject __xor__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__xor__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__xor__(other); - } - - public PyObject __rxor__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__rxor__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__rxor__(other); - } - - public PyObject __lt__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__lt__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__lt__(other); - } - - public PyObject __le__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__le__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__le__(other); - } - - public PyObject __gt__(PyObject other) { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__gt__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res==Py.NotImplemented) - return null; - return res; - } - return super.__gt__(other); - } - - ... [truncated message content] |
From: <fwi...@us...> - 2009-10-26 20:28:01
|
Revision: 6907 http://jython.svn.sourceforge.net/jython/?rev=6907&view=rev Author: fwierzbicki Date: 2009-10-26 20:11:44 +0000 (Mon, 26 Oct 2009) Log Message: ----------- Remove unused variable. Modified Paths: -------------- trunk/jython/src/org/python/compiler/Module.java Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2009-10-26 19:51:10 UTC (rev 6906) +++ trunk/jython/src/org/python/compiler/Module.java 2009-10-26 20:11:44 UTC (rev 6907) @@ -581,7 +581,6 @@ c.ldc(classfile.name); c.invokespecial(classfile.name, "<init>", sig(Void.TYPE, String.class)); c.invokevirtual(classfile.name, "getMain", sig(PyCode.class)); - String bootstrap = Type.getDescriptor(CodeBootstrap.class); c.invokestatic(p(CodeLoader.class), CodeLoader.SIMPLE_FACTORY_METHOD_NAME, sig(CodeBootstrap.class, PyCode.class)); c.aload(0); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-26 19:51:18
|
Revision: 6906 http://jython.svn.sourceforge.net/jython/?rev=6906&view=rev Author: fwierzbicki Date: 2009-10-26 19:51:10 +0000 (Mon, 26 Oct 2009) Log Message: ----------- Remove another unused variable. Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-26 19:34:45 UTC (rev 6905) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-26 19:51:10 UTC (rev 6906) @@ -116,7 +116,6 @@ private Map<String, SymInfo> tbl; private ScopeInfo my_scope; private boolean optimizeGlobals = true; - private Vector<String> names; private String className; private Stack<Label> continueLabels, breakLabels; private Stack<ExceptionHandler> exceptionHandlers; @@ -261,7 +260,6 @@ this.cflags = cflags; my_scope = scope; - names = scope.names; tbl = scope.tbl; optimizeGlobals = checkOptimizeGlobals(fast_locals, scope); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-26 19:34:53
|
Revision: 6905 http://jython.svn.sourceforge.net/jython/?rev=6905&view=rev Author: fwierzbicki Date: 2009-10-26 19:34:45 +0000 (Mon, 26 Oct 2009) Log Message: ----------- Remove unused imports and fields. Reduce visibility of parse and makeStrings. Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-26 06:38:28 UTC (rev 6904) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-26 19:34:45 UTC (rev 6905) @@ -93,7 +93,6 @@ import org.python.core.PyTuple; import org.python.core.PyUnicode; import org.python.core.ThreadState; -import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; @@ -104,15 +103,8 @@ private static final Object Exit = new Integer(1); private static final Object NoExit = null; - private static final int GET = 0; - private static final int SET = 1; - private static final int DEL = 2; - private static final int AUGGET = 3; - private static final int AUGSET = 4; private Module module; - private ClassWriter cw; private Code code; - private CodeCompiler mrefs; private CompilerFlags cflags; private int temporary; private expr_contextType augmode; @@ -148,9 +140,6 @@ this.module = module; this.print_results = print_results; - mrefs = this; - cw = module.classfile.cw; - continueLabels = new Stack<Label>(); breakLabels = new Stack<Label>(); exceptionHandlers = new Stack<ExceptionHandler>(); @@ -262,7 +251,7 @@ return fast_locals && !scope.exec && !scope.from_import_star; } - public void parse(mod node, Code code, + void parse(mod node, Code code, boolean fast_locals, String className, boolean classBody, ScopeInfo scope, CompilerFlags cflags) throws Exception { @@ -1631,7 +1620,7 @@ return null; } - public static int makeStrings(Code c, Collection<String> names) + static int makeStrings(Code c, Collection<String> names) throws IOException { if (names != null) { c.iconst(names.size()); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |