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-13 02:32:07
|
Revision: 6854 http://jython.svn.sourceforge.net/jython/?rev=6854&view=rev Author: pjenvey Date: 2009-10-13 02:31:45 +0000 (Tue, 13 Oct 2009) Log Message: ----------- move the cached objectGetattribute out of PyObject to ease bootstrapping Modified Paths: -------------- trunk/jython/src/org/python/core/Deriveds.java trunk/jython/src/org/python/core/PyObject.java Modified: trunk/jython/src/org/python/core/Deriveds.java =================================================================== --- trunk/jython/src/org/python/core/Deriveds.java 2009-10-12 05:04:37 UTC (rev 6853) +++ trunk/jython/src/org/python/core/Deriveds.java 2009-10-13 02:31:45 UTC (rev 6854) @@ -6,8 +6,12 @@ */ public class Deriveds { + /** object.__getattribute__ descriptor, cached for use by __findattr_ex__. */ + private static final PyObject objectGetattribute = + PyObject.TYPE.__findattr__("__getattribute__"); + /** - * Derived's __findattr_ex__ implementation. + * Deriveds' __findattr_ex__ implementation. * * This resides here (in org.python.core) because it manipulates PyType, and doesn't * call any of the Derived classes' superclass methods. @@ -34,7 +38,7 @@ type.getName())); } - if (getattribute == PyObject.objectGetattribute) { + if (getattribute == objectGetattribute) { type.setUsesObjectGetattribute(true); } pyName = PyString.fromInterned(name); Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2009-10-12 05:04:37 UTC (rev 6853) +++ trunk/jython/src/org/python/core/PyObject.java 2009-10-13 02:31:45 UTC (rev 6854) @@ -38,9 +38,6 @@ /** Primitives classes their wrapper classes. */ private static final Map<Class<?>, Class<?>> primitiveMap = Generic.map(); - /** object.__getattribute__ descriptor, cached for use by Deriveds.__findattr_ex__. */ - static final PyObject objectGetattribute; - static { primitiveMap.put(Character.TYPE, Character.class); primitiveMap.put(Boolean.TYPE, Boolean.class); @@ -55,8 +52,6 @@ Py.writeWarning("init", "Bootstrap types weren't encountered in bootstrapping: " + Py.BOOTSTRAP_TYPES); } - - objectGetattribute = TYPE.__findattr__("__getattribute__"); } public PyObject(PyType objtype) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-12 05:04:59
|
Revision: 6853 http://jython.svn.sourceforge.net/jython/?rev=6853&view=rev Author: pjenvey Date: 2009-10-12 05:04:37 +0000 (Mon, 12 Oct 2009) Log Message: ----------- port Armin Rigo's global mro cache optimization from PyPy/CPython 2.6. unlike their's this version is thread safe (non-blocking). being global, it may become less optimal when shared by many PythonInterpreters/PySystemStates this provides a nice attribute lookup speedup but it can slow down silly things like class attribute counters (maybe due to our extra allocation around the cache invalidation) refs http://bugs.python.org/issue1700288 Modified Paths: -------------- trunk/jython/src/org/python/core/PyJavaType.java trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/src/org/python/core/PyJavaType.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaType.java 2009-10-10 06:05:26 UTC (rev 6852) +++ trunk/jython/src/org/python/core/PyJavaType.java 2009-10-12 05:04:37 UTC (rev 6853) @@ -421,7 +421,7 @@ // If one of our superclasses has something defined for this name, check if its a bean // property, and if so, try to fill in any gaps in our property from there PyObject fromType[] = new PyObject[] { null }; - PyObject superForName = lookup_where(prop.__name__, fromType); + PyObject superForName = lookup_where_mro(prop.__name__, fromType); if (superForName instanceof PyBeanProperty) { PyBeanProperty superProp = ((PyBeanProperty)superForName); // If it has a set method and we don't, take it regardless. If the types don't line @@ -608,7 +608,7 @@ } String nmethname = normalize(meth.getName()); PyObject[] where = new PyObject[1]; - PyObject obj = lookup_where(nmethname, where); + PyObject obj = lookup_where_mro(nmethname, where); if (obj == null) { // Nothing in our supertype hierarchy defines something with this name, so it // must not be visible there. Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2009-10-10 06:05:26 UTC (rev 6852) +++ trunk/jython/src/org/python/core/PyType.java 2009-10-12 05:04:37 UTC (rev 6853) @@ -9,6 +9,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.atomic.AtomicReferenceArray; import org.python.expose.ExposeAsSuperclass; import org.python.expose.ExposedDelete; @@ -81,12 +82,18 @@ /** Whether this type's __getattribute__ is object.__getattribute__. */ private volatile boolean usesObjectGetattribute; + /** MethodCacheEntry version tag. */ + private volatile Object versionTag = new Object(); + /** The number of __slots__ defined. */ private int numSlots; private ReferenceQueue<PyType> subclasses_refq = new ReferenceQueue<PyType>(); private Set<WeakReference<PyType>> subclasses = Generic.set(); + /** Global mro cache. */ + private static final MethodCache methodCache = new MethodCache(); + /** Mapping of Java classes to their PyTypes. */ private static Map<Class<?>, PyType> class_to_type; @@ -185,6 +192,7 @@ type.createAllSlots(!base.needs_userdict, !base.needs_weakref); type.ensureAttributes(); + type.invalidateMethodCache(); for (PyObject cur : type.bases) { if (cur instanceof PyType) @@ -277,7 +285,7 @@ if (wantWeak) { createWeakrefSlot(); } - needs_finalizer = lookup("__del__") != null; + needs_finalizer = lookup_mro("__del__") != null; } /** @@ -494,8 +502,8 @@ } private void fillHasSetAndDelete() { - has_set = lookup("__set__") != null; - has_delete = lookup("__delete__") != null; + has_set = lookup_mro("__set__") != null; + has_delete = lookup_mro("__delete__") != null; } public PyObject getStatic() { @@ -1042,17 +1050,50 @@ } /** - * INTERNAL lookup for name through mro objects' dicts + * Attribute lookup for name through mro objects' dicts. Lookups are cached. * - * @param name - * attribute name (must be interned) + * @param name attribute name (must be interned) * @return found object or null */ public PyObject lookup(String name) { return lookup_where(name, null); } + /** + * Attribute lookup for name directly through mro objects' dicts. This isn't cached, + * and should generally only be used during the bootstrapping of a type. + * + * @param name attribute name (must be interned) + * @return found object or null + */ + protected PyObject lookup_mro(String name) { + return lookup_where_mro(name, null); + } + + /** + * Attribute lookup for name through mro objects' dicts. Lookups are cached. + * + * Returns where in the mro the attribute was found at where[0]. + * + * @param name attribute name (must be interned) + * @param where Where in the mro the attribute was found is written to index 0 + * @return found object or null + */ public PyObject lookup_where(String name, PyObject[] where) { + return methodCache.lookup_where(this, name, where); + } + + /** + * Attribute lookup for name through mro objects' dicts. This isn't cached, and should + * generally only be used during the bootstrapping of a type. + * + * Returns where in the mro the attribute was found at where[0]. + * + * @param name attribute name (must be interned) + * @param where Where in the mro the attribute was found is written to index 0 + * @return found object or null + */ + protected PyObject lookup_where_mro(String name, PyObject[] where) { PyObject[] mro = this.mro; if (mro == null) { return null; @@ -1176,7 +1217,8 @@ class_to_type.put(c, newtype); newtype.builtin = true; - newtype.init(c,needsInners); + newtype.init(c, needsInners); + newtype.invalidateMethodCache(); return newtype; } @@ -1313,6 +1355,7 @@ } void postSetattr(String name) { + invalidateMethodCache(); if (name == "__set__") { if (!has_set && lookup("__set__") != null) { traverse_hierarchy(false, new OnType() { @@ -1363,8 +1406,8 @@ postDelattr(name); } - void postDelattr(String name) { + invalidateMethodCache(); if (name == "__set__") { if (has_set && lookup("__set__") == null) { traverse_hierarchy(false, new OnType() { @@ -1400,6 +1443,19 @@ } } + /** + * Invalidate this type's MethodCache entries. *Must* be called after any modification + * to __dict__ (or anything else affecting attribute lookups). + */ + protected void invalidateMethodCache() { + traverse_hierarchy(false, new OnType() { + public boolean onType(PyType type) { + type.versionTag = new Object(); + return false; + } + }); + } + public PyObject __call__(PyObject[] args, String[] keywords) { return type___call__(args, keywords); } @@ -1449,6 +1505,7 @@ throw Py.ValueError("__name__ must not contain null bytes"); } setName(nameStr); + invalidateMethodCache(); } public void setName(String name) { @@ -1701,4 +1758,107 @@ mro = newMro.toArray(new PyObject[newMro.size()]); } } + + /** + * A thead safe, non-blocking version of Armin Rigo's mro cache. + */ + static class MethodCache { + + /** The fixed size cache. */ + private final AtomicReferenceArray<MethodCacheEntry> table; + + /** Size of the cache exponent (2 ** SIZE_EXP). */ + public static final int SIZE_EXP = 11; + + public MethodCache() { + table = new AtomicReferenceArray<MethodCacheEntry>(1 << SIZE_EXP); + clear(); + } + + public void clear() { + int length = table.length(); + for (int i = 0; i < length; i++) { + table.set(i, MethodCacheEntry.EMPTY); + } + } + + public PyObject lookup_where(PyType type, String name, PyObject where[]) { + Object versionTag = type.versionTag; + int index = indexFor(versionTag, name); + MethodCacheEntry entry = table.get(index); + + if (entry.isValid(versionTag, name)) { + return entry.get(where); + } + + // Always cache where + if (where == null) { + where = new PyObject[1]; + } + PyObject value = type.lookup_where_mro(name, where); + if (isCacheableName(name)) { + // CAS isn't totally necessary here but is possibly more correct. Cache by + // the original version before the lookup, if it's changed since then + // we'll cache a bad entry. Bad entries and CAS failures aren't a concern + // as subsequent lookups will sort themselves out + table.compareAndSet(index, entry, new MethodCacheEntry(versionTag, name, where[0], + value)); + } + return value; + } + + /** + * Return the table index for type version/name. + */ + private static int indexFor(Object version, String name) { + long hash = version.hashCode() * name.hashCode(); + return (int)hash >>> (Integer.SIZE - SIZE_EXP); + } + + /** + * Determine if name is cacheable. + * + * Since the cache can keep references to names alive longer than usual, it avoids + * caching unusually large strings. + */ + private static boolean isCacheableName(String name) { + return name.length() <= 100; + } + + static class MethodCacheEntry extends WeakReference<PyObject> { + + /** Version of the entry, a PyType.versionTag. */ + private final Object version; + + /** The name of the attribute. */ + private final String name; + + /** Where in the mro the value was found. */ + private final WeakReference<PyObject> where; + + static final MethodCacheEntry EMPTY = new MethodCacheEntry(); + + private MethodCacheEntry() { + this(null, null, null, null); + } + + public MethodCacheEntry(Object version, String name, PyObject where, PyObject value) { + super(value); + this.version = version; + this.name = name; + this.where = new WeakReference<PyObject>(where); + } + + public boolean isValid(Object version, String name) { + return this.version == version && this.name == name; + } + + public PyObject get(PyObject[] where) { + if (where != null) { + where[0] = this.where.get(); + } + return get(); + } + } + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-10 06:05:43
|
Revision: 6852 http://jython.svn.sourceforge.net/jython/?rev=6852&view=rev Author: pjenvey Date: 2009-10-10 06:05:26 +0000 (Sat, 10 Oct 2009) Log Message: ----------- add a flag to sys as a faster SystemRestart check for the code objects. otherwise currentThread().isInterrupted() is now a noticable performance hit Modified Paths: -------------- trunk/jython/src/org/python/core/PyBaseCode.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/PyTableCode.java trunk/jython/src/org/python/util/jython.java Modified: trunk/jython/src/org/python/core/PyBaseCode.java =================================================================== --- trunk/jython/src/org/python/core/PyBaseCode.java 2009-10-10 05:44:16 UTC (rev 6851) +++ trunk/jython/src/org/python/core/PyBaseCode.java 2009-10-10 06:05:26 UTC (rev 6852) @@ -98,7 +98,7 @@ // Check for interruption, which is used for restarting the interpreter // on Jython - if (Thread.currentThread().isInterrupted()) { + if (ts.systemState._systemRestart && Thread.currentThread().isInterrupted()) { throw new PyException(_systemrestart.SystemRestart); } return ret; Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2009-10-10 05:44:16 UTC (rev 6851) +++ trunk/jython/src/org/python/core/PySystemState.java 2009-10-10 06:05:26 UTC (rev 6852) @@ -144,6 +144,9 @@ private int recursionlimit = 1000; + /** true when a SystemRestart is triggered. */ + public boolean _systemRestart = false; + public PySystemState() { initialize(); modules = new PyStringMap(); Modified: trunk/jython/src/org/python/core/PyTableCode.java =================================================================== --- trunk/jython/src/org/python/core/PyTableCode.java 2009-10-10 05:44:16 UTC (rev 6851) +++ trunk/jython/src/org/python/core/PyTableCode.java 2009-10-10 06:05:26 UTC (rev 6852) @@ -198,7 +198,7 @@ // Check for interruption, which is used for restarting the interpreter // on Jython - if (Thread.currentThread().isInterrupted()) { + if (ts.systemState._systemRestart && Thread.currentThread().isInterrupted()) { throw new PyException(_systemrestart.SystemRestart); } return ret; Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2009-10-10 05:44:16 UTC (rev 6851) +++ trunk/jython/src/org/python/util/jython.java 2009-10-10 06:05:26 UTC (rev 6852) @@ -355,8 +355,9 @@ * Run any finalizations on the current interpreter in preparation for a SytemRestart. */ public static void shutdownInterpreter() { - // Stop all the active threads + // Stop all the active threads and signal the SystemRestart thread.interruptAllThreads(); + Py.getSystemState()._systemRestart = true; // Close all sockets -- not all of their operations are stopped by // Thread.interrupt (in particular pre-nio sockets) try { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-10 05:44:34
|
Revision: 6851 http://jython.svn.sourceforge.net/jython/?rev=6851&view=rev Author: pjenvey Date: 2009-10-10 05:44:16 +0000 (Sat, 10 Oct 2009) Log Message: ----------- after a SystemRestart don't reset PySystemState until after the exitfuncs are called, otherwise some strange problems can occur Modified Paths: -------------- trunk/jython/NEWS trunk/jython/src/org/python/util/jython.java Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-10-09 18:32:33 UTC (rev 6850) +++ trunk/jython/NEWS 2009-10-10 05:44:16 UTC (rev 6851) @@ -3,6 +3,8 @@ Jython 2.5.2a1 Bugs Fixed - [ 1478 ] defaultdict & weakref.WeakKeyDictionary [TypeError: first argument must be callable] + - Fix runtime issues during exitfuncs triggered via SystemRestart (such as + during Django or Pylons development mode reloading) Jython 2.5.1rc3 Bugs Fixed Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2009-10-09 18:32:33 UTC (rev 6850) +++ trunk/jython/src/org/python/util/jython.java 2009-10-10 05:44:16 UTC (rev 6851) @@ -254,9 +254,11 @@ // Shutdown this instance... shouldRestart = true; shutdownInterpreter(); + interp.cleanup(); // ..reset the state... Py.setSystemState(new PySystemState()); // ...and start again + return; } else { Py.printException(t); if (!opts.interactive) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-09 18:32:41
|
Revision: 6850 http://jython.svn.sourceforge.net/jython/?rev=6850&view=rev Author: fwierzbicki Date: 2009-10-09 18:32:33 +0000 (Fri, 09 Oct 2009) Log Message: ----------- Make all of the fields in CodeCompiler private except "yields". I plan to make "yields" private as well, but that's going to take some surgery on Module. 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-09 03:17:04 UTC (rev 6849) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-09 18:32:33 UTC (rev 6850) @@ -102,32 +102,34 @@ public class CodeCompiler extends Visitor implements Opcodes, ClassConstants { - static final Object Exit = new Integer(1); - static final Object NoExit = null; - static final int GET = 0; - static final int SET = 1; - static final int DEL = 2; - static final int AUGGET = 3; - static final int AUGSET = 4; - Module module; - ClassWriter cw; - Code code; - CodeCompiler mrefs; - CompilerFlags cflags; - int temporary; - expr_contextType augmode; - int augtmp1; - int augtmp2; - int augtmp3; - int augtmp4; - boolean fast_locals, print_results; - Map<String, SymInfo> tbl; - ScopeInfo my_scope; - boolean optimizeGlobals = true; - Vector<String> names; - String className; - Stack<Label> continueLabels, breakLabels; - Stack<ExceptionHandler> exceptionHandlers; + 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; + private int augtmp1; + private int augtmp2; + private int augtmp3; + private int augtmp4; + private boolean fast_locals, print_results; + 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; + + //Module uses this, otherwise I'd make it private. Vector<Label> yields = new Vector<Label>(); /* @@ -138,8 +140,8 @@ * PyCode, in other words: each 'function'. When returning through * finally's all the exceptionHandlers are executed. */ - public int bcfLevel = 0; - int yield_count = 0; + private int bcfLevel = 0; + private int yield_count = 0; private Stack<String> stack = new Stack<String>(); public CodeCompiler(Module module, boolean print_results) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-09 03:17:23
|
Revision: 6849 http://jython.svn.sourceforge.net/jython/?rev=6849&view=rev Author: pjenvey Date: 2009-10-09 03:17:04 +0000 (Fri, 09 Oct 2009) Log Message: ----------- rearrange/cleanup by exposing __call__ with ThreadState Modified Paths: -------------- trunk/jython/src/org/python/core/PyFunction.java Modified: trunk/jython/src/org/python/core/PyFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyFunction.java 2009-10-08 03:30:17 UTC (rev 6848) +++ trunk/jython/src/org/python/core/PyFunction.java 2009-10-09 03:17:04 UTC (rev 6849) @@ -348,7 +348,8 @@ @Override public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, PyObject arg2, PyObject arg3) { - return func_code.call(state, arg0, arg1, arg2, arg3, func_globals, func_defaults, func_closure); + return func_code.call(state, arg0, arg1, arg2, arg3, func_globals, func_defaults, + func_closure); } @Override @@ -363,17 +364,17 @@ @Override public PyObject __call__(PyObject[] args, String[] keywords) { - return function___call__(args, keywords); + return __call__(Py.getThreadState(), args, keywords); } @Override public PyObject __call__(ThreadState state, PyObject[] args, String[] keywords) { - return func_code.call(state, args, keywords, func_globals, func_defaults, func_closure); + return function___call__(state, args, keywords); } @ExposedMethod(doc = BuiltinDocs.function___call___doc) - final PyObject function___call__(PyObject[] args, String[] keywords) { - return __call__(Py.getThreadState(), args, keywords); + final PyObject function___call__(ThreadState state, PyObject[] args, String[] keywords) { + return func_code.call(state, args, keywords, func_globals, func_defaults, func_closure); } @Override @@ -382,8 +383,10 @@ } @Override - public PyObject __call__(ThreadState state, PyObject arg1, PyObject[] args, String[] keywords) { - return func_code.call(state, arg1, args, keywords, func_globals, func_defaults, func_closure); + public PyObject __call__(ThreadState state, PyObject arg1, PyObject[] args, + String[] keywords) { + return func_code.call(state, arg1, args, keywords, func_globals, func_defaults, + func_closure); } @Override This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-08 03:30:28
|
Revision: 6848 http://jython.svn.sourceforge.net/jython/?rev=6848&view=rev Author: fwierzbicki Date: 2009-10-08 03:30:17 +0000 (Thu, 08 Oct 2009) Log Message: ----------- Coding standards / Cleanup. 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-08 02:33:20 UTC (rev 6847) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-08 03:30:17 UTC (rev 6848) @@ -1,5 +1,4 @@ // Copyright (c) Corporation for National Research Initiatives - package org.python.compiler; import java.io.IOException; @@ -103,37 +102,30 @@ public class CodeCompiler extends Visitor implements Opcodes, ClassConstants { - static final Object Exit=new Integer(1); - static final Object NoExit=null; - - static final int GET=0; - static final int SET=1; - static final int DEL=2; - static final int AUGGET=3; - static final int AUGSET=4; - + static final Object Exit = new Integer(1); + static final Object NoExit = null; + static final int GET = 0; + static final int SET = 1; + static final int DEL = 2; + static final int AUGGET = 3; + static final int AUGSET = 4; Module module; ClassWriter cw; Code code; CodeCompiler mrefs; CompilerFlags cflags; - int temporary; expr_contextType augmode; int augtmp1; int augtmp2; int augtmp3; int augtmp4; - boolean fast_locals, print_results; - Map<String, SymInfo> tbl; ScopeInfo my_scope; - boolean optimizeGlobals = true; Vector<String> names; String className; - Stack<Label> continueLabels, breakLabels; Stack<ExceptionHandler> exceptionHandlers; Vector<Label> yields = new Vector<Label>(); @@ -147,9 +139,7 @@ * finally's all the exceptionHandlers are executed. */ public int bcfLevel = 0; - int yield_count = 0; - private Stack<String> stack = new Stack<String>(); public CodeCompiler(Module module, boolean print_results) { @@ -181,7 +171,7 @@ code.iconst(idx); code.putfield(p(PyFrame.class), "f_lasti", "I"); } - + private void loadf_back() throws Exception { code.getfield(p(PyFrame.class), "f_back", ci(PyFrame.class)); } @@ -235,40 +225,45 @@ code.astore(augtmp1); code.aload(augtmp1); - if (count >= 2) + if (count >= 2) { code.aload(augtmp2); - if (count >= 3) + } + if (count >= 3) { code.aload(augtmp3); - if (count >= 4) + } + if (count >= 4) { code.aload(augtmp4); + } } private void restoreAugTmps(PythonTree node, int count) throws Exception { - code.aload(augtmp1); - code.freeLocal(augtmp1); - if (count == 1) - return; - code.aload(augtmp2); - code.freeLocal(augtmp2); - if (count == 2) - return; - code.aload(augtmp3); - code.freeLocal(augtmp3); - if (count == 3) - return; - code.aload(augtmp4); - code.freeLocal(augtmp4); + code.aload(augtmp1); + code.freeLocal(augtmp1); + if (count == 1) { + return; + } + code.aload(augtmp2); + code.freeLocal(augtmp2); + if (count == 2) { + return; + } + code.aload(augtmp3); + code.freeLocal(augtmp3); + if (count == 3) { + return; + } + code.aload(augtmp4); + code.freeLocal(augtmp4); } static boolean checkOptimizeGlobals(boolean fast_locals, ScopeInfo scope) { - return fast_locals&&!scope.exec&&!scope.from_import_star; + return fast_locals && !scope.exec && !scope.from_import_star; } public void parse(mod node, Code code, - boolean fast_locals, String className, - boolean classBody, ScopeInfo scope, CompilerFlags cflags) - throws Exception - { + boolean fast_locals, String className, + boolean classBody, ScopeInfo scope, CompilerFlags cflags) + throws Exception { this.fast_locals = fast_locals; this.className = className; this.code = code; @@ -279,7 +274,7 @@ tbl = scope.tbl; optimizeGlobals = checkOptimizeGlobals(fast_locals, scope); - + if (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 @@ -313,17 +308,15 @@ @Override public Object visitModule(org.python.antlr.ast.Module suite) - throws Exception - { + throws Exception { if (suite.getInternalBody().size() > 0 && - suite.getInternalBody().get(0) instanceof Expr && - ((Expr) suite.getInternalBody().get(0)).getInternalValue() instanceof Str) - { + suite.getInternalBody().get(0) instanceof Expr && + ((Expr) suite.getInternalBody().get(0)).getInternalValue() instanceof Str) { loadFrame(); code.ldc("__doc__"); visit(((Expr) suite.getInternalBody().get(0)).getInternalValue()); code.invokevirtual(p(PyFrame.class), "setglobal", sig(Void.TYPE, String.class, - PyObject.class)); + PyObject.class)); } traverse(suite); return null; @@ -333,9 +326,9 @@ public Object visitExpression(Expression node) throws Exception { if (my_scope.generator && node.getInternalBody() != null) { module.error("'return' with argument inside generator", - true, node); + true, node); } - return visitReturn(new Return(node,node.getInternalBody()), true); + return visitReturn(new Return(node, node.getInternalBody()), true); } public int makeArray(java.util.List<? extends PythonTree> nodes) throws Exception { @@ -343,10 +336,11 @@ // the caller is responsible for freeing. int n; - if (nodes == null) + if (nodes == null) { n = 0; - else + } else { n = nodes.size(); + } int array = code.getLocal(ci(PyObject[].class)); if (n == 0) { @@ -357,7 +351,7 @@ code.anewarray(p(PyObject.class)); code.astore(array); - for(int i=0; i<n; i++) { + for (int i = 0; i < n; i++) { visit(nodes.get(i)); code.aload(array); code.swap(); @@ -379,8 +373,7 @@ public void getDocString(java.util.List<stmt> suite) throws Exception { if (suite.size() > 0 && suite.get(0) instanceof Expr && - ((Expr) suite.get(0)).getInternalValue() instanceof Str) - { + ((Expr) suite.get(0)).getInternalValue() instanceof Str) { visit(((Expr) suite.get(0)).getInternalValue()); } else { code.aconst_null(); @@ -388,20 +381,24 @@ } public boolean makeClosure(ScopeInfo scope) throws Exception { - if (scope == null || scope.freevars == null) return false; + if (scope == null || scope.freevars == null) { + return false; + } int n = scope.freevars.size(); - if (n == 0) return false; + if (n == 0) { + return false; + } int tmp = code.getLocal(ci(PyObject[].class)); code.iconst(n); code.anewarray(p(PyObject.class)); code.astore(tmp); Map<String, SymInfo> upTbl = scope.up.tbl; - for(int i=0; i<n; i++) { + for (int i = 0; i < n; i++) { code.aload(tmp); code.iconst(i); loadFrame(); - for(int j = 1; j < scope.distance; j++) { + for (int j = 1; j < scope.distance; j++) { loadf_back(); } SymInfo symInfo = upTbl.get(scope.freevars.elementAt(i)); @@ -437,23 +434,23 @@ scope.setup_closure(); scope.dump(); - module.codeConstant(new Suite(node,node.getInternalBody()), name, true, - className, false, false, - node.getLine(), scope, cflags).get(code); + module.codeConstant(new Suite(node, node.getInternalBody()), name, true, + className, false, false, + node.getLine(), scope, cflags).get(code); getDocString(node.getInternalBody()); if (!makeClosure(scope)) { code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, - PyObject[].class, PyCode.class, PyObject.class)); + PyObject[].class, PyCode.class, PyObject.class)); } else { code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, - PyObject[].class, PyCode.class, PyObject.class, PyObject[].class)); + PyObject[].class, PyCode.class, PyObject.class, PyObject[].class)); } - + applyDecorators(node.getInternalDecorator_list()); - set(new Name(node,node.getInternalName(), expr_contextType.Store)); + set(new Name(node, node.getInternalName(), expr_contextType.Store)); return null; } @@ -461,14 +458,15 @@ if (decorators != null && !decorators.isEmpty()) { int res = storeTop(); for (expr decorator : decorators) { - visit(decorator); stackProduce(); + visit(decorator); + stackProduce(); } for (int i = decorators.size(); i > 0; i--) { stackConsume(); loadThreadState(); code.aload(res); code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, - ThreadState.class, PyObject.class)); + ThreadState.class, PyObject.class)); code.astore(res); } code.aload(res); @@ -490,7 +488,7 @@ } @Override - public Object visitAssign(Assign node) throws Exception { + public Object visitAssign(Assign node) throws Exception { setline(node); visit(node.getInternalValue()); if (node.getInternalTargets().size() == 1) { @@ -528,10 +526,10 @@ visit(node.getInternalValues().get(i)); if (node.getInternalNl() && i == node.getInternalValues().size() - 1) { code.invokestatic(p(Py.class), "println", sig(Void.TYPE, PyObject.class, - PyObject.class)); + PyObject.class)); } else { - code.invokestatic(p(Py.class), "printComma", sig(Void.TYPE, PyObject.class, - PyObject.class)); + code.invokestatic(p(Py.class), "printComma", sig(Void.TYPE, PyObject.class, + PyObject.class)); } } else { visit(node.getInternalValues().get(i)); @@ -539,7 +537,7 @@ code.invokestatic(p(Py.class), "println", sig(Void.TYPE, PyObject.class)); } else { code.invokestatic(p(Py.class), "printComma", sig(Void.TYPE, - PyObject.class)); + PyObject.class)); } } @@ -598,15 +596,15 @@ } int stackState = saveStack(); - + if (node.getInternalValue() != null) { visit(node.getInternalValue()); } else { getNone(); } - + setLastI(++yield_count); - + saveLocals(); code.areturn(); @@ -615,7 +613,7 @@ code.label(restart); restoreLocals(); restoreStack(stackState); - + loadFrame(); code.invokevirtual(p(PyFrame.class), "getGeneratorInput", sig(Object.class)); code.dup(); @@ -626,14 +624,14 @@ code.athrow(); code.label(done2); code.checkcast(p(PyObject.class)); - + return null; } - + private void stackProduce() { stackProduce(p(PyObject.class)); } - + private void stackProduce(String signature) { stack.push(signature); } @@ -641,7 +639,7 @@ private void stackConsume() { stackConsume(1); } - + private void stackConsume(int numItems) { for (int i = 0; i < numItems; i++) { stack.pop(); @@ -680,7 +678,7 @@ private void restoreStack(int array) throws Exception { if (stack.size() > 0) { - int i = stack.size() -1; + int i = stack.size() - 1; for (String signature : stack) { if (p(ThreadState.class).equals(signature)) { loadThreadState(); @@ -699,7 +697,7 @@ private void restoreLocals() throws Exception { endExceptionHandlers(); - + Vector<String> v = code.getActiveLocals(); loadFrame(); @@ -710,8 +708,9 @@ for (int i = 0; i < v.size(); i++) { String type = v.elementAt(i); - if (type == null) + if (type == null) { continue; + } code.aload(locals); code.iconst(i); code.aaload(); @@ -730,8 +729,7 @@ * variables without the verifier thinking we might jump out of our * handling with an exception. */ - private void endExceptionHandlers() - { + private void endExceptionHandlers() { Label end = new Label(); code.label(end); for (int i = 0; i < exceptionHandlers.size(); ++i) { @@ -740,8 +738,7 @@ } } - private void restartExceptionHandlers() - { + private void restartExceptionHandlers() { Label start = new Label(); code.label(start); for (int i = 0; i < exceptionHandlers.size(); ++i) { @@ -759,15 +756,17 @@ for (int i = 0; i < v.size(); i++) { String type = v.elementAt(i); - if (type == null) + if (type == null) { continue; + } code.aload(locals); code.iconst(i); //code.checkcast(code.pool.Class(p(Object.class))); if (i == 2222) { code.aconst_null(); - } else + } else { code.aload(i); + } code.aastore(); } @@ -777,7 +776,6 @@ code.freeLocal(locals); } - @Override public Object visitReturn(Return node) throws Exception { return visitReturn(node, false); @@ -790,9 +788,10 @@ } int tmp = 0; if (node.getInternalValue() != null) { - if (my_scope.generator) + if (my_scope.generator) { throw new ParseException("'return' with argument " + - "inside generator", node); + "inside generator", node); + } visit(node.getInternalValue()); tmp = code.getReturnLocal(); code.astore(tmp); @@ -813,9 +812,18 @@ @Override public Object visitRaise(Raise node) throws Exception { setline(node); - if (node.getInternalType() != null) { visit(node.getInternalType()); stackProduce(); } - if (node.getInternalInst() != null) { visit(node.getInternalInst()); stackProduce(); } - if (node.getInternalTback() != null) { visit(node.getInternalTback()); stackProduce(); } + if (node.getInternalType() != null) { + visit(node.getInternalType()); + stackProduce(); + } + if (node.getInternalInst() != null) { + visit(node.getInternalInst()); + stackProduce(); + } + if (node.getInternalTback() != null) { + visit(node.getInternalTback()); + stackProduce(); + } if (node.getInternalType() == null) { code.invokestatic(p(Py.class), "makeException", sig(PyException.class)); } else if (node.getInternalInst() == null) { @@ -824,11 +832,11 @@ } else if (node.getInternalTback() == null) { stackConsume(2); code.invokestatic(p(Py.class), "makeException", sig(PyException.class, PyObject.class, - PyObject.class)); + PyObject.class)); } else { stackConsume(3); code.invokestatic(p(Py.class), "makeException", sig(PyException.class, PyObject.class, - PyObject.class, PyObject.class)); + PyObject.class, PyObject.class)); } code.athrow(); return Exit; @@ -845,23 +853,23 @@ code.ldc(name); loadFrame(); code.invokestatic(p(imp.class), "importOneAs", sig(PyObject.class, String.class, - PyFrame.class)); + PyFrame.class)); } else { String name = a.getInternalName(); asname = name; - if (asname.indexOf('.') > 0) + if (asname.indexOf('.') > 0) { asname = asname.substring(0, asname.indexOf('.')); + } code.ldc(name); loadFrame(); code.invokestatic(p(imp.class), "importOne", sig(PyObject.class, String.class, - PyFrame.class)); + PyFrame.class)); } set(new Name(a, asname, expr_contextType.Store)); } return null; } - @Override public Object visitImportFrom(ImportFrom node) throws Exception { Future.checkFromFuture(node); // future stmt support @@ -890,18 +898,19 @@ "' because it is a nested function", true, node); } - + loadFrame(); code.invokestatic(p(imp.class), "importAll", sig(Void.TYPE, String.class, - PyFrame.class)); + PyFrame.class)); } else { java.util.List<String> fromNames = new ArrayList<String>();//[names.size()]; java.util.List<String> asnames = new ArrayList<String>();//[names.size()]; for (int i = 0; i < aliases.size(); i++) { fromNames.add(aliases.get(i).getInternalName()); asnames.add(aliases.get(i).getInternalAsname()); - if (asnames.get(i) == null) + if (asnames.get(i) == null) { asnames.set(i, fromNames.get(i)); + } } int strArray = makeStrings(code, fromNames); code.aload(strArray); @@ -919,7 +928,7 @@ code.iconst(node.getInternalLevel()); } code.invokestatic(p(imp.class), "importFrom", sig(PyObject[].class, String.class, - String[].class, PyFrame.class, Integer.TYPE)); + String[].class, PyFrame.class, Integer.TYPE)); int tmp = storeTop(); for (int i = 0; i < aliases.size(); i++) { code.aload(tmp); @@ -960,7 +969,7 @@ //do the real work here stackConsume(3); code.invokestatic(p(Py.class), "exec", sig(Void.TYPE, PyObject.class, PyObject.class, - PyObject.class)); + PyObject.class)); return null; } @@ -968,7 +977,7 @@ public Object visitAssert(Assert node) throws Exception { setline(node); Label end_of_assert = new Label(); - + /* First do an if __debug__: */ loadFrame(); emitGetGlobal("__debug__"); @@ -978,8 +987,8 @@ code.ifeq(end_of_assert); /* Now do the body of the assert. If PyObject.__nonzero__ is true, - then the assertion succeeded, the message portion should not be - processed. Otherwise, the message will be processed. */ + then the assertion succeeded, the message portion should not be + processed. Otherwise, the message will be processed. */ visit(node.getInternalTest()); code.invokevirtual(p(PyObject.class), "__nonzero__", sig(Boolean.TYPE)); @@ -987,24 +996,23 @@ code.ifne(end_of_assert); /* Visit the message part of the assertion, or pass Py.None */ - if( node.getInternalMsg() != null ) { - visit(node.getInternalMsg()); + if (node.getInternalMsg() != null) { + visit(node.getInternalMsg()); } else { - getNone(); + getNone(); } - + /* Push exception type onto stack(AssertionError) */ loadFrame(); emitGetGlobal("AssertionError"); - + code.swap(); // The type is the first argument, but the message could be a yield - + code.invokestatic(p(Py.class), "makeException", sig(PyException.class, PyObject.class, - PyObject.class)); - /* Raise assertion error. Only executes this logic if assertion - failed */ + PyObject.class)); + /* Raise assertion error. Only executes this logic if assertion failed */ code.athrow(); - + /* And finally set the label for the end of it all */ code.label(end_of_assert); @@ -1012,8 +1020,7 @@ } public Object doTest(Label end_of_if, If node, int index) - throws Exception - { + throws Exception { Label end_of_suite = new Label(); setline(node.getInternalTest()); @@ -1024,8 +1031,9 @@ Object exit = suite(node.getInternalBody()); - if (end_of_if != null && exit == null) + if (end_of_if != null && exit == null) { code.goto_(end_of_if); + } code.label(end_of_suite); @@ -1039,12 +1047,14 @@ @Override public Object visitIf(If node) throws Exception { Label end_of_if = null; - if (node.getInternalOrelse() != null) + if (node.getInternalOrelse() != null) { end_of_if = new Label(); + } Object exit = doTest(end_of_if, node, 0); - if (end_of_if != null) + if (end_of_if != null) { code.label(end_of_if); + } return exit; } @@ -1083,7 +1093,6 @@ bcfLevel = savebcf; } - @Override public Object visitWhile(While node) throws Exception { int savebcf = beginLoop(); @@ -1178,11 +1187,10 @@ } public void exceptionTest(int exc, Label end_of_exceptions, - TryExcept node, int index) - throws Exception - { + TryExcept node, int index) + throws Exception { for (int i = 0; i < node.getInternalHandlers().size(); i++) { - ExceptHandler handler = (ExceptHandler)node.getInternalHandlers().get(i); + ExceptHandler handler = (ExceptHandler) node.getInternalHandlers().get(i); //setline(name); Label end_of_self = new Label(); @@ -1192,12 +1200,12 @@ //get specific exception visit(handler.getInternalType()); code.invokevirtual(p(PyException.class), "match", sig(Boolean.TYPE, - PyObject.class)); + PyObject.class)); code.ifeq(end_of_self); } else { - if (i != node.getInternalHandlers().size()-1) { + if (i != node.getInternalHandlers().size() - 1) { throw new ParseException( - "default 'except:' must be last", handler); + "default 'except:' must be last", handler); } } @@ -1216,10 +1224,8 @@ code.athrow(); } - @Override - public Object visitTryFinally(TryFinally node) throws Exception - { + public Object visitTryFinally(TryFinally node) throws Exception { Label start = new Label(); Label end = new Label(); Label handlerStart = new Label(); @@ -1259,8 +1265,8 @@ code.aload(excLocal); loadFrame(); - code.invokestatic(p(Py.class), "addTraceback", sig(Void.TYPE, Throwable.class, - PyFrame.class)); + code.invokestatic(p(Py.class), "addTraceback", + sig(Void.TYPE, Throwable.class, PyFrame.class)); inlineFinally(inFinally); code.aload(excLocal); @@ -1284,19 +1290,19 @@ code.label(end); handler.exceptionEnds.addElement(end); // also exiting the try: portion of this particular finally - } + } if (handler.isFinallyHandler()) { handler.finalBody(this); } } - + private void reenterProtectedBody(ExceptionHandler handler) throws Exception { // restart exception coverage Label restart = new Label(); code.label(restart); handler.exceptionStarts.addElement(restart); } - + /** * Inline the finally handling code for levels down to the levelth parent * (0 means all). This takes care to avoid having more nested finallys @@ -1314,9 +1320,9 @@ ExceptionHandler handler = poppedHandlers.pop(); reenterProtectedBody(handler); exceptionHandlers.push(handler); - } - } - + } + } + @Override public Object visitTryExcept(TryExcept node) throws Exception { Label start = new Label(); @@ -1334,15 +1340,16 @@ code.label(end); handler.exceptionEnds.addElement(end); - if (exit == null) + if (exit == null) { code.goto_(handler_end); + } code.label(handler_start); loadFrame(); code.invokestatic(p(Py.class), "setException", sig(PyException.class, Throwable.class, - PyFrame.class)); + PyFrame.class)); int exc = code.getFinallyLocal(p(Throwable.class)); code.astore(exc); @@ -1373,10 +1380,11 @@ } public Object suite(java.util.List<stmt> stmts) throws Exception { - for(stmt s: stmts) { + for (stmt s : stmts) { Object exit = visit(s); - if (exit != null) + if (exit != null) { return Exit; + } } return null; } @@ -1389,12 +1397,12 @@ code.dup(); code.invokevirtual(p(PyObject.class), "__nonzero__", sig(Boolean.TYPE)); switch (node.getInternalOp()) { - case Or : - code.ifne(end); - break; - case And : - code.ifeq(end); - break; + case Or: + code.ifne(end); + break; + case And: + code.ifeq(end); + break; } code.pop(); visit(node.getInternalValues().get(i)); @@ -1403,7 +1411,6 @@ return null; } - @Override public Object visitCompare(Compare node) throws Exception { int last = code.getLocal(p(PyObject.class)); @@ -1414,7 +1421,7 @@ code.astore(last); int n = node.getInternalOps().size(); - for(int i = 0; i < n - 1; i++) { + for (int i = 0; i < n - 1; i++) { visit(node.getInternalComparators().get(i)); code.aload(last); code.swap(); @@ -1427,10 +1434,10 @@ code.ifeq(end); } - visit(node.getInternalComparators().get(n-1)); + visit(node.getInternalComparators().get(n - 1)); code.aload(last); code.swap(); - visitCmpop(node.getInternalOps().get(n-1)); + visitCmpop(node.getInternalOps().get(n - 1)); if (n > 1) { code.astore(result); @@ -1448,16 +1455,36 @@ public void visitCmpop(cmpopType op) throws Exception { String name = null; switch (op) { - case Eq: name = "_eq"; break; - case NotEq: name = "_ne"; break; - case Lt: name = "_lt"; break; - case LtE: name = "_le"; break; - case Gt: name = "_gt"; break; - case GtE: name = "_ge"; break; - case Is: name = "_is"; break; - case IsNot: name = "_isnot"; break; - case In: name = "_in"; break; - case NotIn: name = "_notin"; break; + case Eq: + name = "_eq"; + break; + case NotEq: + name = "_ne"; + break; + case Lt: + name = "_lt"; + break; + case LtE: + name = "_le"; + break; + case Gt: + name = "_gt"; + break; + case GtE: + name = "_ge"; + break; + case Is: + name = "_is"; + break; + case IsNot: + name = "_isnot"; + break; + case In: + name = "_in"; + break; + case NotIn: + name = "_notin"; + break; } code.invokevirtual(p(PyObject.class), name, sig(PyObject.class, PyObject.class)); } @@ -1470,18 +1497,42 @@ stackConsume(); String name = null; switch (node.getInternalOp()) { - case Add: name = "_add"; break; - case Sub: name = "_sub"; break; - case Mult: name = "_mul"; break; - case Div: name = "_div"; break; - case Mod: name = "_mod"; break; - case Pow: name = "_pow"; break; - case LShift: name = "_lshift"; break; - case RShift: name = "_rshift"; break; - case BitOr: name = "_or"; break; - case BitXor: name = "_xor"; break; - case BitAnd: name = "_and"; break; - case FloorDiv: name = "_floordiv"; break; + case Add: + name = "_add"; + break; + case Sub: + name = "_sub"; + break; + case Mult: + name = "_mul"; + break; + case Div: + name = "_div"; + break; + case Mod: + name = "_mod"; + break; + case Pow: + name = "_pow"; + break; + case LShift: + name = "_lshift"; + break; + case RShift: + name = "_rshift"; + break; + case BitOr: + name = "_or"; + break; + case BitXor: + name = "_xor"; + break; + case BitAnd: + name = "_and"; + break; + case FloorDiv: + name = "_floordiv"; + break; } if (node.getInternalOp() == operatorType.Div && module.getFutures().areDivisionOn()) { @@ -1490,16 +1541,24 @@ code.invokevirtual(p(PyObject.class), name, sig(PyObject.class, PyObject.class)); return null; } - + @Override public Object visitUnaryOp(UnaryOp node) throws Exception { visit(node.getInternalOperand()); String name = null; switch (node.getInternalOp()) { - case Invert: name = "__invert__"; break; - case Not: name = "__not__"; break; - case UAdd: name = "__pos__"; break; - case USub: name = "__neg__"; break; + case Invert: + name = "__invert__"; + break; + case Not: + name = "__not__"; + break; + case UAdd: + name = "__pos__"; + break; + case USub: + name = "__neg__"; + break; } code.invokevirtual(p(PyObject.class), name, sig(PyObject.class)); return null; @@ -1519,18 +1578,42 @@ code.swap(); String name = null; switch (node.getInternalOp()) { - case Add: name = "_iadd"; break; - case Sub: name = "_isub"; break; - case Mult: name = "_imul"; break; - case Div: name = "_idiv"; break; - case Mod: name = "_imod"; break; - case Pow: name = "_ipow"; break; - case LShift: name = "_ilshift"; break; - case RShift: name = "_irshift"; break; - case BitOr: name = "_ior"; break; - case BitXor: name = "_ixor"; break; - case BitAnd: name = "_iand"; break; - case FloorDiv: name = "_ifloordiv"; break; + case Add: + name = "_iadd"; + break; + case Sub: + name = "_isub"; + break; + case Mult: + name = "_imul"; + break; + case Div: + name = "_idiv"; + break; + case Mod: + name = "_imod"; + break; + case Pow: + name = "_ipow"; + break; + case LShift: + name = "_ilshift"; + break; + case RShift: + name = "_irshift"; + break; + case BitOr: + name = "_ior"; + break; + case BitXor: + name = "_ixor"; + break; + case BitAnd: + name = "_iand"; + break; + case FloorDiv: + name = "_ifloordiv"; + break; } if (node.getInternalOp() == operatorType.Div && module.getFutures().areDivisionOn()) { name = "_itruediv"; @@ -1546,10 +1629,8 @@ return null; } - public static int makeStrings(Code c, Collection<String> names) - throws IOException - { + throws IOException { if (names != null) { c.iconst(names.size()); } else { @@ -1570,68 +1651,76 @@ } return strings; } - + public Object invokeNoKeywords(Attribute node, java.util.List<expr> values) - throws Exception - { + throws Exception { String name = getName(node.getInternalAttr()); - visit(node.getInternalValue()); stackProduce(); + visit(node.getInternalValue()); + stackProduce(); code.ldc(name); code.invokevirtual(p(PyObject.class), "__getattr__", sig(PyObject.class, String.class)); - loadThreadState(); stackProduce(p(ThreadState.class)); + loadThreadState(); + stackProduce(p(ThreadState.class)); switch (values.size()) { - case 0: - stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class)); - break; - case 1: - visit(values.get(0)); - stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, + case 0: + stackConsume(2); // target + ts + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class)); + break; + case 1: + visit(values.get(0)); + stackConsume(2); // target + ts + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class, PyObject.class)); + break; + case 2: + visit(values.get(0)); + stackProduce(); + visit(values.get(1)); + stackConsume(3); // target + ts + arguments + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class, PyObject.class, PyObject.class)); + break; + case 3: + visit(values.get(0)); + stackProduce(); + visit(values.get(1)); + stackProduce(); + visit(values.get(2)); + stackConsume(4); // target + ts + arguments + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class, PyObject.class, PyObject.class, PyObject.class)); + break; + case 4: + visit(values.get(0)); + stackProduce(); + visit(values.get(1)); + stackProduce(); + visit(values.get(2)); + stackProduce(); + visit(values.get(3)); + stackConsume(5); // target + ts + arguments + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class, PyObject.class, PyObject.class, PyObject.class, PyObject.class)); - break; - case 2: - visit(values.get(0)); stackProduce(); - visit(values.get(1)); - stackConsume(3); // target + ts + arguments - code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, - PyObject.class, PyObject.class)); - break; - case 3: - visit(values.get(0)); stackProduce(); - visit(values.get(1)); stackProduce(); - visit(values.get(2)); - stackConsume(4); // target + ts + arguments - code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, - PyObject.class, PyObject.class, PyObject.class)); - break; - case 4: - visit(values.get(0)); stackProduce(); - visit(values.get(1)); stackProduce(); - visit(values.get(2)); stackProduce(); - visit(values.get(3)); - stackConsume(5); // target + ts + arguments - code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, - PyObject.class, PyObject.class, PyObject.class, PyObject.class)); - break; - default: - int argArray = makeArray(values); - code.aload(argArray); - code.freeLocal(argArray); - stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, - PyObject[].class)); - break; + break; + default: + int argArray = makeArray(values); + code.aload(argArray); + code.freeLocal(argArray); + stackConsume(2); // target + ts + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class, PyObject[].class)); + break; } return null; } - @Override public Object visitCall(Call node) throws Exception { - java.util.List<String> keys = new ArrayList<String>();//[node.keywords.size()]; - java.util.List<expr> values = new ArrayList<expr>();//[node.args.size() + keys.size()]; + java.util.List<String> keys = new ArrayList<String>(); + java.util.List<expr> values = new ArrayList<expr>(); for (int i = 0; i < node.getInternalArgs().size(); i++) { values.add(node.getInternalArgs().get(i)); } @@ -1640,41 +1729,45 @@ values.add(node.getInternalKeywords().get(i).getInternalValue()); } - if ((node.getInternalKeywords() == null || node.getInternalKeywords().size() == 0)&& node.getInternalStarargs() == null && - node.getInternalKwargs() == null && node.getInternalFunc() instanceof Attribute) - { + if ((node.getInternalKeywords() == null || node.getInternalKeywords().size() == 0) && + node.getInternalStarargs() == null && node.getInternalKwargs() == null && + node.getInternalFunc() instanceof Attribute) { return invokeNoKeywords((Attribute) node.getInternalFunc(), values); } - visit(node.getInternalFunc()); stackProduce(); + visit(node.getInternalFunc()); + stackProduce(); if (node.getInternalStarargs() != null || node.getInternalKwargs() != null) { int argArray = makeArray(values); int strArray = makeStrings(code, keys); - if (node.getInternalStarargs() == null) + if (node.getInternalStarargs() == null) { code.aconst_null(); - else + } else { visit(node.getInternalStarargs()); + } stackProduce(); - if (node.getInternalKwargs() == null) + if (node.getInternalKwargs() == null) { code.aconst_null(); - else + } else { visit(node.getInternalKwargs()); + } stackProduce(); - + code.aload(argArray); code.aload(strArray); code.freeLocal(argArray); code.freeLocal(strArray); code.dup2_x2(); code.pop2(); - + stackConsume(3); // target + starargs + kwargs code.invokevirtual(p(PyObject.class), "_callextra", sig(PyObject.class, - PyObject[].class, String[].class, PyObject.class, PyObject.class)); + PyObject[].class, String[].class, PyObject.class, PyObject.class)); } else if (keys.size() > 0) { - loadThreadState(); stackProduce(p(ThreadState.class)); + loadThreadState(); + stackProduce(p(ThreadState.class)); int argArray = makeArray(values); int strArray = makeStrings(code, keys); code.aload(argArray); @@ -1683,60 +1776,66 @@ code.freeLocal(strArray); stackConsume(2); // target + ts code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, - PyObject[].class, String[].class)); + PyObject[].class, String[].class)); } else { - loadThreadState(); stackProduce(p(ThreadState.class)); + loadThreadState(); + stackProduce(p(ThreadState.class)); switch (values.size()) { - case 0: - stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + case 0: + stackConsume(2); // target + ts + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class)); - break; - case 1: - visit(values.get(0)); - stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + break; + case 1: + visit(values.get(0)); + stackConsume(2); // target + ts + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, PyObject.class)); - break; - case 2: - visit(values.get(0)); stackProduce(); - visit(values.get(1)); - stackConsume(3); // target + ts + arguments - code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + break; + case 2: + visit(values.get(0)); + stackProduce(); + visit(values.get(1)); + stackConsume(3); // target + ts + arguments + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, PyObject.class, PyObject.class)); - break; - case 3: - visit(values.get(0)); stackProduce(); - visit(values.get(1)); stackProduce(); - visit(values.get(2)); - stackConsume(4); // target + ts + arguments - code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + break; + case 3: + visit(values.get(0)); + stackProduce(); + visit(values.get(1)); + stackProduce(); + visit(values.get(2)); + stackConsume(4); // target + ts + arguments + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, PyObject.class, PyObject.class, PyObject.class)); - break; - case 4: - visit(values.get(0)); stackProduce(); - visit(values.get(1)); stackProduce(); - visit(values.get(2)); stackProduce(); - visit(values.get(3)); - stackConsume(5); // target + ts + arguments - code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + break; + case 4: + visit(values.get(0)); + stackProduce(); + visit(values.get(1)); + stackProduce(); + visit(values.get(2)); + stackProduce(); + visit(values.get(3)); + stackConsume(5); // target + ts + arguments + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, PyObject.class, PyObject.class, PyObject.class, PyObject.class)); - break; - default: - int argArray = makeArray(values); - code.aload(argArray); - code.freeLocal(argArray); - stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + break; + default: + int argArray = makeArray(values); + code.aload(argArray); + code.freeLocal(argArray); + stackConsume(2); // target + ts + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, PyObject[].class)); - break; + break; } } return null; } - public Object Slice(Subscript node, Slice slice) throws Exception { expr_contextType ctx = node.getInternalCtx(); if (ctx == expr_contextType.AugStore && augmode == expr_contextType.Store) { @@ -1745,23 +1844,27 @@ } else { visit(node.getInternalValue()); stackProduce(); - if (slice.getInternalLower() != null) + if (slice.getInternalLower() != null) { visit(slice.getInternalLower()); - else + } else { code.aconst_null(); + } stackProduce(); - if (slice.getInternalUpper() != null) + if (slice.getInternalUpper() != null) { visit(slice.getInternalUpper()); - else + } else { code.aconst_null(); + } stackProduce(); - if (slice.getInternalStep() != null) + if (slice.getInternalStep() != null) { visit(slice.getInternalStep()); - else + } else { code.aconst_null(); + } stackProduce(); - if (node.getInternalCtx() == expr_contextType.AugStore && augmode == expr_contextType.Load) { + if (node.getInternalCtx() == expr_contextType.AugStore && + augmode == expr_contextType.Load) { saveAugTmps(node, 4); ctx = expr_contextType.Load; } @@ -1769,20 +1872,20 @@ } switch (ctx) { - case Del: - code.invokevirtual(p(PyObject.class), "__delslice__", sig(Void.TYPE, PyObject.class, + case Del: + code.invokevirtual(p(PyObject.class), "__delslice__", sig(Void.TYPE, PyObject.class, PyObject.class, PyObject.class)); - return null; - case Load: - code.invokevirtual(p(PyObject.class), "__getslice__", sig(PyObject.class, + return null; + case Load: + code.invokevirtual(p(PyObject.class), "__getslice__", sig(PyObject.class, PyObject.class, PyObject.class, PyObject.class)); - return null; - case Param: - case Store: - code.aload(temporary); - code.invokevirtual(p(PyObject.class), "__setslice__", sig(Void.TYPE, PyObject.class, + return null; + case Param: + case Store: + code.aload(temporary); + code.invokevirtual(p(PyObject.class), "__setslice__", sig(Void.TYPE, PyObject.class, PyObject.class, PyObject.class, PyObject.class)); - return null; + return null; } return null; @@ -1796,33 +1899,38 @@ int value = temporary; expr_contextType ctx = node.getInternalCtx(); - if (node.getInternalCtx() == expr_contextType.AugStore && augmode == expr_contextType.Store) { + if (node.getInternalCtx() == expr_contextType.AugStore && + augmode == expr_contextType.Store) { restoreAugTmps(node, 2); ctx = expr_contextType.Store; } else { - visit(node.getInternalValue()); stackProduce(); + visit(node.getInternalValue()); + stackProduce(); visit(node.getInternalSlice()); stackConsume(); - if (node.getInternalCtx() == expr_contextType.AugStore && augmode == expr_contextType.Load) { + if (node.getInternalCtx() == expr_contextType.AugStore && + augmode == expr_contextType.Load) { saveAugTmps(node, 2); ctx = expr_contextType.Load; } } switch (ctx) { - case Del: - code.invokevirtual(p(PyObject.class), "__delitem__", sig(Void.TYPE, PyObject.class)); - return null; - case Load: - code.invokevirtual(p(PyObject.class), "__getitem__", sig(PyObject.class, PyObject.class)); - return null; - case Param: - case Store: - code.aload(value); - code.invokevirtual(p(PyObject.class), "__setitem__", sig(Void.TYPE, PyObject.class, - PyObject.class)); - return null; + case Del: + code.invokevirtual(p(PyObject.class), "__delitem__", + sig(Void.TYPE, PyObject.class)); + return null; + case Load: + code.invokevirtual(p(PyObject.class), "__getitem__", + sig(PyObject.class, PyObject.class)); + return null; + case Param: + case Store: + code.aload(value); + code.invokevirtual(p(PyObject.class), "__setitem__", + sig(Void.TYPE, PyObject.class, PyObject.class)); + return null; } return null; } @@ -1848,32 +1956,35 @@ public Object visitAttribute(Attribute node) throws Exception { expr_contextType ctx = node.getInternalCtx(); - if (node.getInternalCtx() == expr_contextType.AugStore && augmode == expr_contextType.Store) { + if (node.getInternalCtx() == expr_contextType.AugStore && + augmode == expr_contextType.Store) { restoreAugTmps(node, 2); ctx = expr_contextType.Store; } else { visit(node.getInternalValue()); code.ldc(getName(node.getInternalAttr())); - if (node.getInternalCtx() == expr_contextType.AugStore && augmode == expr_contextType.Load) { + if (node.getInternalCtx() == expr_contextType.AugStore && + augmode == expr_contextType.Load) { saveAugTmps(node, 2); ctx = expr_contextType.Load; } } switch (ctx) { - case Del: - code.invokevirtual(p(PyObject.class), "__delattr__", sig(Void.TYPE, String.class)); - return null; - case Load: - code.invokevirtual(p(PyObject.class), "__getattr__", sig(PyObject.class, String.class)); - return null; - case Param: - case Store: - code.aload(temporary); - code.invokevirtual(p(PyObject.class), "__setattr__", sig(Void.TYPE, String.class, - PyObject.class)); - return null; + case Del: + code.invokevirtual(p(PyObject.class), "__delattr__", sig(Void.TYPE, String.class)); + return null; + case Load: + code.invokevirtual(p(PyObject.class), "__getattr__", + sig(PyObject.class, String.class)); + return null; + case Param: + case Store: + code.aload(temporary); + code.invokevirtual(p(PyObject.class), "__setattr__", + sig(Void.TYPE, String.class, PyObject.class)); + return null; } return null; } @@ -1881,8 +1992,8 @@ public Object seqSet(java.util.List<expr> nodes) throws Exception { code.aload(temporary); code.iconst(nodes.size()); - code.invokestatic(p(Py.class), "unpackSequence", sig(PyObject[].class, PyObject.class, - Integer.TYPE)); + code.invokestatic(p(Py.class), "unpackSequence", + sig(PyObject[].class, PyObject.class, Integer.TYPE)); int tmp = code.getLocal("[org/python/core/PyObject"); code.astore(tmp); @@ -1899,7 +2010,7 @@ } public Object seqDel(java.util.List<expr> nodes) throws Exception { - for (expr e: nodes) { + for (expr e : nodes) { visit(e); } return null; @@ -1907,12 +2018,13 @@ @Override public Object visitTuple(Tuple node) throws Exception { - /* if (mode ==AUGSET) - throw new ParseException( - "augmented assign to tuple not possible", node); */ - if (node.getInternalCtx() == expr_contextType.Store) return seqSet(node.getInternalElts()); - if (node.getInternalCtx() == expr_contextType.Del) return seqDel(node.getInternalElts()); - + if (node.getInternalCtx() == expr_contextType.Store) { + return seqSet(node.getInternalElts()); + } + if (node.getInternalCtx() == expr_contextType.Del) { + return seqDel(node.getInternalElts()); + } + int content = makeArray(node.getInternalElts()); code.new_(p(PyTuple.class)); @@ -1926,9 +2038,13 @@ @Override public Object visitList(List node) throws Exception { - if (node.getInternalCtx() == expr_contextType.Store) return seqSet(node.getInternalElts()); - if (node.getInternalCtx() == expr_contextType.Del) return seqDel(node.getInternalElts()); - + if (node.getInternalCtx() == expr_contextType.Store) { + return seqSet(node.getInternalElts()); + } + if (node.getInternalCtx() == expr_contextType.Del) { + return seqDel(node.getInternalElts()); + } + int content = makeArray(node.getInternalElts()); code.new_(p(PyList.class)); @@ -1951,26 +2067,28 @@ code.ldc("append"); code.invokevirtual(p(PyObject.class), "__getattr__", sig(PyObject.class, String.class)); - String tmp_append ="_[" + node.getLine() + "_" + node.getCharPositionInLine() + "]"; + String tmp_append = "_[" + node.getLine() + "_" + node.getCharPositionInLine() + "]"; set(new Name(node, tmp_append, expr_contextType.Store)); java.util.List<expr> args = new ArrayList<expr>(); args.add(node.getInternalElt()); - stmt n = new Expr(node, new Call(node, new Name(node, tmp_append, expr_contextType.Load), - args, - new ArrayList<keyword>(), null, null)); + stmt n = new Expr(node, new Call(node, new Name(node, tmp_append, expr_contextType.Load), + args, + new ArrayList<keyword>(), null, null)); for (int i = node.getInternalGenerators().size() - 1; i >= 0; i--) { comprehension lc = node.getInternalGenerators().get(i); for (int j = lc.getInternalIfs().size() - 1; j >= 0; j--) { java.util.List<stmt> body = new ArrayList<stmt>(); body.add(n); - n = new If(lc.getInternalIfs().get(j), lc.getInternalIfs().get(j), body, new ArrayList<stmt>()); + n = new If(lc.getInternalIfs().get(j), lc.getInternalIfs().get(j), body, + new ArrayList<stmt>()); } java.util.List<stmt> body = new ArrayList<stmt>(); body.add(n); - n = new For(lc,lc.getInternalTarget(), lc.getInternalIter(), body, new ArrayList<stmt>()); + n = new For(lc, lc.getInternalTarget(), lc.getInternalIter(), body, + new ArrayList<stmt>()); } visit(n); java.util.List<expr> targets = new ArrayList<expr>(); @@ -1988,7 +2106,7 @@ elts.add(node.getInternalValues().get(i)); } int content = makeArray(elts); - + code.new_(p(PyDictionary.class)); code.dup(); code.aload(content); @@ -2010,7 +2128,7 @@ //Add a return node onto the outside of suite; java.util.List<stmt> bod = new ArrayList<stmt>(); - bod.add(new Return(node,node.getInternalBody())); + bod.add(new Return(node, node.getInternalBody())); mod retSuite = new Suite(node, bod); setline(node); @@ -2020,32 +2138,31 @@ int defaultsArray = makeArray(scope.ac.getDefaults()); code.new_(p(PyFunction.class)); - + code.dup(); code.aload(defaultsArray); code.freeLocal(defaultsArray); loadFrame(); code.getfield(p(PyFrame.class), "f_globals", ci(PyObject.class)); - + code.swap(); scope.setup_closure(); scope.dump(); module.codeConstant(retSuite, name, true, className, - false, false, node.getLine(), scope, cflags).get(code); + false, false, node.getLine(), scope, cflags).get(code); if (!makeClosure(scope)) { code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, - PyObject[].class, PyCode.class)); + PyObject[].class, PyCode.class)); } else { code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, - PyObject[].class, Py... [truncated message content] |
From: <fwi...@us...> - 2009-10-08 02:33:28
|
Revision: 6847 http://jython.svn.sourceforge.net/jython/?rev=6847&view=rev Author: fwierzbicki Date: 2009-10-08 02:33:20 +0000 (Thu, 08 Oct 2009) Log Message: ----------- Coding standards / Cleanup. 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-07 19:16:54 UTC (rev 6846) +++ trunk/jython/src/org/python/compiler/Module.java 2009-10-08 02:33:20 UTC (rev 6847) @@ -1,5 +1,4 @@ // Copyright (c) Corporation for National Research Initiatives - package org.python.compiler; import java.io.IOException; @@ -39,6 +38,7 @@ import static org.python.util.CodegenUtils.*; class PyIntegerConstant extends Constant implements ClassConstants, Opcodes { + final int value; PyIntegerConstant(int value) { @@ -64,15 +64,15 @@ @Override public boolean equals(Object o) { if (o instanceof PyIntegerConstant) { - return ((PyIntegerConstant)o).value == value; + return ((PyIntegerConstant) o).value == value; } else { return false; } } } -class PyFloatConstant extends Constant implements ClassConstants, Opcodes -{ +class PyFloatConstant extends Constant implements ClassConstants, Opcodes { + final double value; PyFloatConstant(double value) { @@ -92,21 +92,21 @@ @Override public int hashCode() { - return (int)value; + return (int) value; } @Override public boolean equals(Object o) { if (o instanceof PyFloatConstant) { - return ((PyFloatConstant)o).value == value; + return ((PyFloatConstant) o).value == value; } else { return false; } } } -class PyComplexConstant extends Constant implements ClassConstants, Opcodes -{ +class PyComplexConstant extends Constant implements ClassConstants, Opcodes { + final double value; PyComplexConstant(double value) { @@ -126,21 +126,21 @@ @Override public int hashCode() { - return (int)value; + return (int) value; } @Override public boolean equals(Object o) { if (o instanceof PyComplexConstant) { - return ((PyComplexConstant)o).value == value; + return ((PyComplexConstant) o).value == value; } else { return false; } } } -class PyStringConstant extends Constant implements ClassConstants, Opcodes -{ +class PyStringConstant extends Constant implements ClassConstants, Opcodes { + final String value; PyStringConstant(String value) { @@ -166,15 +166,15 @@ @Override public boolean equals(Object o) { if (o instanceof PyStringConstant) { - return ((PyStringConstant)o).value.equals(value); + return ((PyStringConstant) o).value.equals(value); } else { return false; } } } -class PyUnicodeConstant extends Constant implements ClassConstants, Opcodes -{ +class PyUnicodeConstant extends Constant implements ClassConstants, Opcodes { + final String value; PyUnicodeConstant(String value) { @@ -200,15 +200,15 @@ @Override public boolean equals(Object o) { if (o instanceof PyUnicodeConstant) { - return ((PyUnicodeConstant)o).value.equals(value); + return ((PyUnicodeConstant) o).value.equals(value); } else { return false; } } } -class PyLongConstant extends Constant implements ClassConstants, Opcodes -{ +class PyLongConstant extends Constant implements ClassConstants, Opcodes { + final String value; PyLongConstant(String value) { @@ -234,15 +234,15 @@ @Override public boolean equals(Object o) { if (o instanceof PyLongConstant) { - return ((PyLongConstant)o).value.equals(value); + return ((PyLongConstant) o).value.equals(value); } else { return false; } } } -class PyCodeConstant extends Constant implements ClassConstants, Opcodes -{ +class PyCodeConstant extends Constant implements ClassConstants, Opcodes { + final String co_name; final int argcount; final List<String> names; @@ -250,19 +250,16 @@ final int co_firstlineno; final boolean arglist, keywordlist; final String fname; - // for nested scopes final List<String> cellvars; final List<String> freevars; final int jy_npurecell; - final int moreflags; - PyCodeConstant(mod tree, String name, boolean fast_locals, String - className, boolean classBody, boolean printResults, int - firstlineno, ScopeInfo scope, org.python.core.CompilerFlags cflags, + PyCodeConstant(mod tree, String name, boolean fast_locals, String className, boolean classBody, + boolean printResults, int firstlineno, ScopeInfo scope, CompilerFlags cflags, Module module) - throws Exception { + throws Exception { this.co_name = name; this.co_firstlineno = firstlineno; @@ -275,7 +272,7 @@ arglist = scope.ac.arglist; keywordlist = scope.ac.keywordlist; argcount = scope.ac.names.size(); - + //Do something to add init_code to tree //XXX: not sure we should be modifying scope.ac in a PyCodeConstant //constructor. @@ -292,16 +289,16 @@ //Better names in the future? if (isJavaIdentifier(name)) { - fname = name+"$"+id; + fname = name + "$" + id; } else { - fname = "f$"+id; + fname = "f$" + id; } //XXX: is fname needed at all, or should we just use "name"? this.name = fname; // !classdef only if (!classBody) { - names = toNameAr(scope.names,false); + names = toNameAr(scope.names, false); } else { names = null; } @@ -328,7 +325,7 @@ } //XXX: this can probably go away now that we can probably just copy the list. - private List<String> toNameAr(List<String> names,boolean nullok) { + private List<String> toNameAr(List<String> names, boolean nullok) { int sz = names.size(); if (sz == 0 && nullok) { return null; @@ -347,7 +344,7 @@ return false; } - for(int i=1; i<chars.length; i++) { + for (int i = 1; i < chars.length; i++) { if (!Character.isJavaIdentifierPart(chars[i])) { return false; } @@ -379,7 +376,7 @@ c.iconst(arglist ? 1 : 0); c.iconst(keywordlist ? 1 : 0); - c.getstatic(module.classfile.name, "self", "L"+module.classfile.name+";"); + c.getstatic(module.classfile.name, "self", "L" + module.classfile.name + ";"); c.iconst(id); @@ -387,38 +384,44 @@ int strArray = CodeCompiler.makeStrings(c, cellvars); c.aload(strArray); c.freeLocal(strArray); - } else + } else { c.aconst_null(); + } if (freevars != null) { int strArray = CodeCompiler.makeStrings(c, freevars); c.aload(strArray); c.freeLocal(strArray); - } else + } else { c.aconst_null(); + } c.iconst(jy_npurecell); c.iconst(moreflags); - c.invokestatic(p(Py.class), "newCode", sig(PyCode.class, Integer.TYPE, - String[].class, String.class, String.class, Integer.TYPE, Boolean.TYPE, - Boolean.TYPE, PyFunctionTable.class, Integer.TYPE, String[].class, - String[].class, Integer.TYPE, Integer.TYPE)); + c.invokestatic(p(Py.class), "newCode", sig(PyCode.class, Integer.TYPE, + String[].class, String.class, String.class, Integer.TYPE, Boolean.TYPE, + Boolean.TYPE, PyFunctionTable.class, Integer.TYPE, String[].class, + String[].class, Integer.TYPE, Integer.TYPE)); c.putstatic(module.classfile.name, name, ci(PyCode.class)); } } -public class Module implements Opcodes, ClassConstants, CompilationContext -{ +public class Module implements Opcodes, ClassConstants, CompilationContext { + ClassFile classfile; Constant filename; String sfilename; Constant mainCode; boolean linenumbers; Future futures; - Hashtable<PythonTree,ScopeInfo> scopes; + Hashtable<PythonTree, ScopeInfo> scopes; + List<PyCodeConstant> codes; long mtime; + /** The pool of Python Constants */ + Hashtable<Constant, Constant> constants; + public Module(String name, String filename, boolean linenumbers) { this(name, filename, linenumbers, org.python.core.imp.NO_MTIME); } @@ -427,8 +430,8 @@ this.linenumbers = linenumbers; this.mtime = mtime; classfile = new ClassFile(name, p(PyFunctionTable.class), - ACC_SYNCHRONIZED | ACC_PUBLIC, mtime); - constants = new Hashtable<Constant,Constant>(); + ACC_SYNCHRONIZED | ACC_PUBLIC, mtime); + constants = new Hashtable<Constant, Constant>(); sfilename = filename; if (filename != null) { this.filename = stringConstant(filename); @@ -437,16 +440,13 @@ } codes = new ArrayList<PyCodeConstant>(); futures = new Future(); - scopes = new Hashtable<PythonTree,ScopeInfo>(); + scopes = new Hashtable<PythonTree, ScopeInfo>(); } public Module(String name) { - this(name, name+".py", true, org.python.core.imp.NO_MTIME); + this(name, name + ".py", true, org.python.core.imp.NO_MTIME); } - // This block of code handles the pool of Python Constants - Hashtable<Constant,Constant> constants; - private Constant findConstant(Constant c) { Constant ret = constants.get(c); if (ret != null) { @@ -455,7 +455,7 @@ ret = c; c.module = this; //More sophisticated name mappings might be nice - c.name = "_"+constants.size(); + c.name = "_" + constants.size(); constants.put(ret, ret); return ret; } @@ -484,25 +484,17 @@ return findConstant(new PyLongConstant(value)); } - List<PyCodeConstant> codes; - PyCodeConstant codeConstant(mod tree, String name, - boolean fast_locals, String className, - boolean classBody, boolean printResults, - int firstlineno, ScopeInfo scope) - throws Exception - { - return codeConstant(tree,name,fast_locals,className,classBody, - printResults,firstlineno,scope,null); + PyCodeConstant codeConstant(mod tree, String name, boolean fast_locals, String className, + boolean classBody, boolean printResults, int firstlineno, ScopeInfo scope) + throws Exception { + return codeConstant(tree, name, fast_locals, className, classBody, + printResults, firstlineno, scope, null); } - PyCodeConstant codeConstant(mod tree, String name, - boolean fast_locals, String className, - boolean classBody, boolean printResults, - int firstlineno, - ScopeInfo scope, - org.python.core.CompilerFlags cflags) - throws Exception - { + PyCodeConstant codeConstant(mod tree, String name, boolean fast_locals, String className, + boolean classBody, boolean printResults, int firstlineno, ScopeInfo scope, + CompilerFlags cflags) + throws Exception { PyCodeConstant code = new PyCodeConstant(tree, name, fast_locals, className, classBody, printResults, firstlineno, scope, cflags, this); @@ -511,9 +503,9 @@ CodeCompiler compiler = new CodeCompiler(this, printResults); Code c = classfile.addMethod( - code.fname, - sig(PyObject.class, PyFrame.class, ThreadState.class), - ACC_PUBLIC); + code.fname, + sig(PyObject.class, PyFrame.class, ThreadState.class), + ACC_PUBLIC); if (classBody) { // Set the class's __module__ to __name__. fails when there's no __name__ @@ -524,7 +516,7 @@ 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)); + PyObject.class)); } Label genswitch = new Label(); @@ -535,16 +527,16 @@ c.label(start); int nparamcell = scope.jy_paramcells.size(); - if(nparamcell > 0) { + if (nparamcell > 0) { Map<String, SymInfo> tbl = scope.tbl; List<String> paramcells = scope.jy_paramcells; - for(int i = 0; i < nparamcell; i++) { + 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)); + Integer.TYPE)); } } @@ -555,11 +547,11 @@ c.aload(1); c.getfield(p(PyFrame.class), "f_lasti", "I"); - Label[] yields = new Label[compiler.yields.size()+1]; + 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); + yields[i] = compiler.yields.get(i - 1); } c.tableswitch(0, yields.length - 1, start, yields); } @@ -567,7 +559,7 @@ return code; } - //This block of code writes out the various standard methods + /** This block of code writes out the various standard methods */ public void addInit() throws IOException { Code c = classfile.addMethod("<init>", sig(Void.TYPE, String.class), ACC_PUBLIC); c.aload(0); @@ -596,7 +588,7 @@ c.invokestatic(p(Py.class), "runMain", sig(Void.TYPE, CodeBootstrap.class, String[].class)); c.return_(); } - + public void addBootstrap() throws IOException { Code c = classfile.addMethod(CodeLoader.GET_BOOTSTRAP_METHOD_NAME, sig(CodeBootstrap.class), ACC_PUBLIC | ACC_STATIC); @@ -607,17 +599,17 @@ } void addConstants(Code c) throws IOException { - classfile.addField("self", "L"+classfile.name+";", ACC_STATIC|ACC_FINAL); + classfile.addField("self", "L" + classfile.name + ";", ACC_STATIC | ACC_FINAL); c.aload(0); - c.putstatic(classfile.name, "self", "L"+classfile.name+";"); + c.putstatic(classfile.name, "self", "L" + classfile.name + ";"); Enumeration e = constants.elements(); while (e.hasMoreElements()) { - Constant constant = (Constant)e.nextElement(); + Constant constant = (Constant) e.nextElement(); constant.put(c); } - for(int i=0; i<codes.size(); i++) { + for (int i = 0; i < codes.size(); i++) { PyCodeConstant pyc = codes.get(i); pyc.put(c); } @@ -627,7 +619,7 @@ public void addFunctions() throws IOException { Code code = classfile.addMethod("call_function", - sig(PyObject.class, Integer.TYPE, PyFrame.class, ThreadState.class), ACC_PUBLIC); + sig(PyObject.class, Integer.TYPE, PyFrame.class, ThreadState.class), ACC_PUBLIC); code.aload(0); // this code.aload(2); // frame @@ -635,16 +627,17 @@ Label def = new Label(); Label[] labels = new Label[codes.size()]; int i; - for(i=0; i<labels.length; i++) + for (i = 0; i < labels.length; i++) { labels[i] = new Label(); + } //Get index for function to call code.iload(1); code.tableswitch(0, labels.length - 1, def, labels); - for(i=0; i<labels.length; i++) { + for (i = 0; i < labels.length; i++) { code.label(labels[i]); code.invokevirtual(classfile.name, (codes.get(i)).fname, sig(PyObject.class, - PyFrame.class, ThreadState.class)); + PyFrame.class, ThreadState.class)); code.areturn(); } code.label(def); @@ -670,45 +663,44 @@ } // Implementation of CompilationContext - public Future getFutures() { return futures; } + public Future getFutures() { + return futures; + } - public String getFilename() { return sfilename; } + public String getFilename() { + return sfilename; + } public ScopeInfo getScopeInfo(PythonTree node) { return scopes.get(node); } - public void error(String msg,boolean err,PythonTree node) - throws Exception - { + public void error(String msg, boolean err, PythonTree node) + throws Exception { if (!err) { try { Py.warning(Py.SyntaxWarning, msg, (sfilename != null) ? sfilename : "?", - node.getLine() ,null, Py.None); + node.getLine(), null, Py.None); return; - } catch(PyException e) { - if (!e.match(Py.SyntaxWarning)) + } catch (PyException e) { + if (!e.match(Py.SyntaxWarning)) { throw e; + } } } - throw new ParseException(msg,node); + throw new ParseException(msg, node); } - public static void compile(mod node, OutputStream ostream, - String name, String filename, - boolean linenumbers, boolean printResults, - CompilerFlags cflags) - throws Exception - { + + public static void compile(mod node, OutputStream ostream, String name, String filename, + boolean linenumbers, boolean printResults, CompilerFlags cflags) + throws Exception { compile(node, ostream, name, filename, linenumbers, printResults, cflags, org.python.core.imp.NO_MTIME); } - public static void compile(mod node, OutputStream ostream, - String name, String filename, - boolean linenumbers, boolean printResults, - CompilerFlags cflags, long mtime) - throws Exception - { + public static void compile(mod node, OutputStream ostream, String name, String filename, + boolean linenumbers, boolean printResults, CompilerFlags cflags, long mtime) + throws Exception { Module module = new Module(name, filename, linenumbers, mtime); if (cflags == null) { cflags = new CompilerFlags(); @@ -719,9 +711,9 @@ //Add __doc__ if it exists Constant main = module.codeConstant(node, "<module>", false, null, false, - printResults, 0, - module.getScopeInfo(node), - cflags); + printResults, 0, + module.getScopeInfo(node), + cflags); module.mainCode = main; module.write(ostream); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-07 19:17:06
|
Revision: 6846 http://jython.svn.sourceforge.net/jython/?rev=6846&view=rev Author: fwierzbicki Date: 2009-10-07 19:16:54 +0000 (Wed, 07 Oct 2009) Log Message: ----------- Make PyCodeConstant an actual constant. Move construction details into PyCodeConstant constructor. Hide more implementation details by making public fields package private. 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-07 02:50:46 UTC (rev 6845) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-07 19:16:54 UTC (rev 6846) @@ -103,20 +103,20 @@ public class CodeCompiler extends Visitor implements Opcodes, ClassConstants { - public static final Object Exit=new Integer(1); - public static final Object NoExit=null; + static final Object Exit=new Integer(1); + static final Object NoExit=null; - public static final int GET=0; - public static final int SET=1; - public static final int DEL=2; - public static final int AUGGET=3; - public static final int AUGSET=4; + static final int GET=0; + static final int SET=1; + static final int DEL=2; + static final int AUGGET=3; + static final int AUGSET=4; - public Module module; - public ClassWriter cw; - public Code code; - public CodeCompiler mrefs; - public CompilerFlags cflags; + Module module; + ClassWriter cw; + Code code; + CodeCompiler mrefs; + CompilerFlags cflags; int temporary; expr_contextType augmode; @@ -125,18 +125,18 @@ int augtmp3; int augtmp4; - public boolean fast_locals, print_results; + boolean fast_locals, print_results; - public Map<String, SymInfo> tbl; - public ScopeInfo my_scope; + Map<String, SymInfo> tbl; + ScopeInfo my_scope; boolean optimizeGlobals = true; - public Vector<String> names; - public String className; + Vector<String> names; + String className; - public Stack<Label> continueLabels, breakLabels; - public Stack<ExceptionHandler> exceptionHandlers; - public Vector<Label> yields = new Vector<Label>(); + Stack<Label> continueLabels, breakLabels; + Stack<ExceptionHandler> exceptionHandlers; + Vector<Label> yields = new Vector<Label>(); /* * break/continue finally's level. This is the lowest level in the @@ -258,8 +258,11 @@ return; code.aload(augtmp4); code.freeLocal(augtmp4); - } + } + static boolean checkOptimizeGlobals(boolean fast_locals, ScopeInfo scope) { + return fast_locals&&!scope.exec&&!scope.from_import_star; + } public void parse(mod node, Code code, boolean fast_locals, String className, @@ -275,7 +278,7 @@ names = scope.names; tbl = scope.tbl; - optimizeGlobals = fast_locals&&!scope.exec&&!scope.from_import_star; + optimizeGlobals = checkOptimizeGlobals(fast_locals, scope); if (scope.max_with_count > 0) { // allocate for all the with-exits we will have in the frame; Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2009-10-07 02:50:46 UTC (rev 6845) +++ trunk/jython/src/org/python/compiler/Module.java 2009-10-07 19:16:54 UTC (rev 6846) @@ -243,24 +243,118 @@ class PyCodeConstant extends Constant implements ClassConstants, Opcodes { - String co_name; - int argcount; - List<String> names; - int id; - int co_firstlineno; - boolean arglist, keywordlist; - String fname; + final String co_name; + final int argcount; + final List<String> names; + final int id; + final int co_firstlineno; + final boolean arglist, keywordlist; + final String fname; // for nested scopes - List<String> cellvars; - List<String> freevars; - int jy_npurecell; + final List<String> cellvars; + final List<String> freevars; + final int jy_npurecell; - int moreflags; + final int moreflags; - PyCodeConstant() { + PyCodeConstant(mod tree, String name, boolean fast_locals, String + className, boolean classBody, boolean printResults, int + firstlineno, ScopeInfo scope, org.python.core.CompilerFlags cflags, + Module module) + throws Exception { + + this.co_name = name; + this.co_firstlineno = firstlineno; + this.module = module; + + //Needed so that moreflags can be final. + int _moreflags = 0; + + if (scope.ac != null) { + arglist = scope.ac.arglist; + keywordlist = scope.ac.keywordlist; + argcount = scope.ac.names.size(); + + //Do something to add init_code to tree + //XXX: not sure we should be modifying scope.ac in a PyCodeConstant + //constructor. + if (scope.ac.init_code.size() > 0) { + scope.ac.appendInitCode((Suite) tree); + } + } else { + arglist = false; + keywordlist = false; + argcount = 0; + } + + id = module.codes.size(); + + //Better names in the future? + if (isJavaIdentifier(name)) { + fname = name+"$"+id; + } else { + fname = "f$"+id; + } + //XXX: is fname needed at all, or should we just use "name"? + this.name = fname; + + // !classdef only + if (!classBody) { + names = toNameAr(scope.names,false); + } else { + names = null; + } + + cellvars = toNameAr(scope.cellvars, true); + freevars = toNameAr(scope.freevars, true); + jy_npurecell = scope.jy_npurecell; + + if (CodeCompiler.checkOptimizeGlobals(fast_locals, scope)) { + _moreflags |= org.python.core.CodeFlag.CO_OPTIMIZED.flag; + } + if (scope.generator) { + _moreflags |= org.python.core.CodeFlag.CO_GENERATOR.flag; + } + if (cflags != null) { + if (cflags.isFlagSet(CodeFlag.CO_GENERATOR_ALLOWED)) { + _moreflags |= org.python.core.CodeFlag.CO_GENERATOR_ALLOWED.flag; + } + if (cflags.isFlagSet(CodeFlag.CO_FUTURE_DIVISION)) { + _moreflags |= org.python.core.CodeFlag.CO_FUTURE_DIVISION.flag; + } + } + moreflags = _moreflags; } + //XXX: this can probably go away now that we can probably just copy the list. + private List<String> toNameAr(List<String> names,boolean nullok) { + int sz = names.size(); + if (sz == 0 && nullok) { + return null; + } + List<String> nameArray = new ArrayList<String>(); + nameArray.addAll(names); + return nameArray; + } + + private boolean isJavaIdentifier(String s) { + char[] chars = s.toCharArray(); + if (chars.length == 0) { + return false; + } + if (!Character.isJavaIdentifierStart(chars[0])) { + return false; + } + + for(int i=1; i<chars.length; i++) { + if (!Character.isJavaIdentifierPart(chars[i])) { + return false; + } + } + return true; + } + void get(Code c) throws IOException { c.getstatic(module.classfile.name, name, ci(PyCode.class)); } @@ -320,7 +414,7 @@ Constant filename; String sfilename; Constant mainCode; - public boolean linenumbers; + boolean linenumbers; Future futures; Hashtable<PythonTree,ScopeInfo> scopes; long mtime; @@ -391,34 +485,6 @@ } List<PyCodeConstant> codes; - private boolean isJavaIdentifier(String s) { - char[] chars = s.toCharArray(); - if (chars.length == 0) { - return false; - } - if (!Character.isJavaIdentifierStart(chars[0])) { - return false; - } - - for(int i=1; i<chars.length; i++) { - if (!Character.isJavaIdentifierPart(chars[i])) { - return false; - } - } - return true; - } - - //XXX: this can probably go away now that we can probably just copy the list. - private List<String> toNameAr(List<String> names,boolean nullok) { - int sz = names.size(); - if (sz == 0 && nullok) { - return null; - } - List<String> nameArray = new ArrayList<String>(); - nameArray.addAll(names); - return nameArray; - } - PyCodeConstant codeConstant(mod tree, String name, boolean fast_locals, String className, boolean classBody, boolean printResults, @@ -429,7 +495,6 @@ printResults,firstlineno,scope,null); } - PyCodeConstant codeConstant(mod tree, String name, boolean fast_locals, String className, boolean classBody, boolean printResults, @@ -438,34 +503,18 @@ org.python.core.CompilerFlags cflags) throws Exception { - PyCodeConstant code = new PyCodeConstant(); - ArgListCompiler ac = (scope != null)?scope.ac:null; + PyCodeConstant code = new PyCodeConstant(tree, name, fast_locals, + className, classBody, printResults, firstlineno, scope, cflags, + this); + codes.add(code); - if (ac != null) { - code.arglist = ac.arglist; - code.keywordlist = ac.keywordlist; - code.argcount = ac.names.size(); - } + CodeCompiler compiler = new CodeCompiler(this, printResults); - code.co_name = name; - code.co_firstlineno = firstlineno; - code.id = codes.size(); - - //Better names in the future? - if (isJavaIdentifier(name)) - code.fname = name+"$"+code.id; - else - code.fname = "f$"+code.id; - - codes.add(code); - Code c = classfile.addMethod( code.fname, sig(PyObject.class, PyFrame.class, ThreadState.class), ACC_PUBLIC); - CodeCompiler compiler = new CodeCompiler(this, printResults); - if (classBody) { // Set the class's __module__ to __name__. fails when there's no __name__ c.aload(1); @@ -485,10 +534,6 @@ Label start = new Label(); c.label(start); - //Do something to add init_code to tree - if (ac != null && ac.init_code.size() > 0) { - ac.appendInitCode((Suite) tree); - } int nparamcell = scope.jy_paramcells.size(); if(nparamcell > 0) { Map<String, SymInfo> tbl = scope.tbl; @@ -504,7 +549,6 @@ } compiler.parse(tree, c, fast_locals, className, classBody, scope, cflags); - // similar to visitResume code in pyasm.py if (scope.generator) { c.label(genswitch); @@ -520,30 +564,6 @@ c.tableswitch(0, yields.length - 1, start, yields); } - // !classdef only - if (!classBody) code.names = toNameAr(compiler.names,false); - - code.cellvars = toNameAr(scope.cellvars, true); - code.freevars = toNameAr(scope.freevars, true); - code.jy_npurecell = scope.jy_npurecell; - - if (compiler.optimizeGlobals) { - code.moreflags |= org.python.core.CodeFlag.CO_OPTIMIZED.flag; - } - if (compiler.my_scope.generator) { - code.moreflags |= org.python.core.CodeFlag.CO_GENERATOR.flag; - } - if (cflags != null) { - if (cflags.isFlagSet(CodeFlag.CO_GENERATOR_ALLOWED)) { - code.moreflags |= org.python.core.CodeFlag.CO_GENERATOR_ALLOWED.flag; - } - if (cflags.isFlagSet(CodeFlag.CO_FUTURE_DIVISION)) { - code.moreflags |= org.python.core.CodeFlag.CO_FUTURE_DIVISION.flag; - } - } - - code.module = this; - code.name = code.fname; 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-07 02:51:08
|
Revision: 6845 http://jython.svn.sourceforge.net/jython/?rev=6845&view=rev Author: pjenvey Date: 2009-10-07 02:50:46 +0000 (Wed, 07 Oct 2009) Log Message: ----------- regen per r6844 Modified Paths: -------------- trunk/jython/src/org/python/antlr/ast/AssertDerived.java trunk/jython/src/org/python/antlr/ast/AssignDerived.java trunk/jython/src/org/python/antlr/ast/AttributeDerived.java trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java trunk/jython/src/org/python/antlr/ast/BinOpDerived.java trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java trunk/jython/src/org/python/antlr/ast/BreakDerived.java trunk/jython/src/org/python/antlr/ast/CallDerived.java trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java trunk/jython/src/org/python/antlr/ast/CompareDerived.java trunk/jython/src/org/python/antlr/ast/ContinueDerived.java trunk/jython/src/org/python/antlr/ast/DeleteDerived.java trunk/jython/src/org/python/antlr/ast/DictDerived.java trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java trunk/jython/src/org/python/antlr/ast/ExecDerived.java trunk/jython/src/org/python/antlr/ast/ExprDerived.java trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java trunk/jython/src/org/python/antlr/ast/ForDerived.java trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java trunk/jython/src/org/python/antlr/ast/GlobalDerived.java trunk/jython/src/org/python/antlr/ast/IfDerived.java trunk/jython/src/org/python/antlr/ast/IfExpDerived.java trunk/jython/src/org/python/antlr/ast/ImportDerived.java trunk/jython/src/org/python/antlr/ast/ImportFromDerived.java trunk/jython/src/org/python/antlr/ast/IndexDerived.java trunk/jython/src/org/python/antlr/ast/InteractiveDerived.java trunk/jython/src/org/python/antlr/ast/LambdaDerived.java trunk/jython/src/org/python/antlr/ast/ListCompDerived.java trunk/jython/src/org/python/antlr/ast/ListDerived.java trunk/jython/src/org/python/antlr/ast/ModuleDerived.java trunk/jython/src/org/python/antlr/ast/NameDerived.java trunk/jython/src/org/python/antlr/ast/NumDerived.java trunk/jython/src/org/python/antlr/ast/PassDerived.java trunk/jython/src/org/python/antlr/ast/PrintDerived.java trunk/jython/src/org/python/antlr/ast/RaiseDerived.java trunk/jython/src/org/python/antlr/ast/ReprDerived.java trunk/jython/src/org/python/antlr/ast/ReturnDerived.java trunk/jython/src/org/python/antlr/ast/SliceDerived.java trunk/jython/src/org/python/antlr/ast/StrDerived.java trunk/jython/src/org/python/antlr/ast/SubscriptDerived.java trunk/jython/src/org/python/antlr/ast/SuiteDerived.java trunk/jython/src/org/python/antlr/ast/TryExceptDerived.java trunk/jython/src/org/python/antlr/ast/TryFinallyDerived.java trunk/jython/src/org/python/antlr/ast/TupleDerived.java trunk/jython/src/org/python/antlr/ast/UnaryOpDerived.java trunk/jython/src/org/python/antlr/ast/WhileDerived.java trunk/jython/src/org/python/antlr/ast/WithDerived.java trunk/jython/src/org/python/antlr/ast/YieldDerived.java trunk/jython/src/org/python/antlr/ast/aliasDerived.java trunk/jython/src/org/python/antlr/ast/argumentsDerived.java trunk/jython/src/org/python/antlr/ast/comprehensionDerived.java trunk/jython/src/org/python/antlr/ast/keywordDerived.java trunk/jython/src/org/python/antlr/op/AddDerived.java trunk/jython/src/org/python/antlr/op/AndDerived.java trunk/jython/src/org/python/antlr/op/AugLoadDerived.java trunk/jython/src/org/python/antlr/op/AugStoreDerived.java trunk/jython/src/org/python/antlr/op/BitAndDerived.java trunk/jython/src/org/python/antlr/op/BitOrDerived.java trunk/jython/src/org/python/antlr/op/BitXorDerived.java trunk/jython/src/org/python/antlr/op/DelDerived.java trunk/jython/src/org/python/antlr/op/DivDerived.java trunk/jython/src/org/python/antlr/op/EqDerived.java trunk/jython/src/org/python/antlr/op/FloorDivDerived.java trunk/jython/src/org/python/antlr/op/GtDerived.java trunk/jython/src/org/python/antlr/op/GtEDerived.java trunk/jython/src/org/python/antlr/op/InDerived.java trunk/jython/src/org/python/antlr/op/InvertDerived.java trunk/jython/src/org/python/antlr/op/IsDerived.java trunk/jython/src/org/python/antlr/op/IsNotDerived.java trunk/jython/src/org/python/antlr/op/LShiftDerived.java trunk/jython/src/org/python/antlr/op/LoadDerived.java trunk/jython/src/org/python/antlr/op/LtDerived.java trunk/jython/src/org/python/antlr/op/LtEDerived.java trunk/jython/src/org/python/antlr/op/ModDerived.java trunk/jython/src/org/python/antlr/op/MultDerived.java trunk/jython/src/org/python/antlr/op/NotDerived.java trunk/jython/src/org/python/antlr/op/NotEqDerived.java trunk/jython/src/org/python/antlr/op/NotInDerived.java trunk/jython/src/org/python/antlr/op/OrDerived.java trunk/jython/src/org/python/antlr/op/ParamDerived.java trunk/jython/src/org/python/antlr/op/PowDerived.java trunk/jython/src/org/python/antlr/op/RShiftDerived.java trunk/jython/src/org/python/antlr/op/StoreDerived.java trunk/jython/src/org/python/antlr/op/SubDerived.java trunk/jython/src/org/python/antlr/op/UAddDerived.java trunk/jython/src/org/python/antlr/op/USubDerived.java trunk/jython/src/org/python/core/ClasspathPyImporterDerived.java trunk/jython/src/org/python/core/PyArrayDerived.java trunk/jython/src/org/python/core/PyBaseExceptionDerived.java trunk/jython/src/org/python/core/PyBooleanDerived.java trunk/jython/src/org/python/core/PyClassMethodDerived.java trunk/jython/src/org/python/core/PyComplexDerived.java trunk/jython/src/org/python/core/PyDictionaryDerived.java trunk/jython/src/org/python/core/PyEnumerateDerived.java trunk/jython/src/org/python/core/PyFileDerived.java trunk/jython/src/org/python/core/PyFloatDerived.java trunk/jython/src/org/python/core/PyFrozenSetDerived.java trunk/jython/src/org/python/core/PyIntegerDerived.java trunk/jython/src/org/python/core/PyListDerived.java trunk/jython/src/org/python/core/PyLongDerived.java trunk/jython/src/org/python/core/PyModuleDerived.java trunk/jython/src/org/python/core/PyObjectDerived.java trunk/jython/src/org/python/core/PyPropertyDerived.java trunk/jython/src/org/python/core/PySetDerived.java trunk/jython/src/org/python/core/PySliceDerived.java trunk/jython/src/org/python/core/PyStringDerived.java trunk/jython/src/org/python/core/PySuperDerived.java trunk/jython/src/org/python/core/PyTupleDerived.java trunk/jython/src/org/python/core/PyTypeDerived.java trunk/jython/src/org/python/core/PyUnicodeDerived.java trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java trunk/jython/src/org/python/modules/random/PyRandomDerived.java trunk/jython/src/org/python/modules/thread/PyLocalDerived.java trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java Modified: trunk/jython/src/org/python/antlr/ast/AssertDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AssertDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/AssertDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/AssignDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AssignDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/AssignDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/AttributeDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AttributeDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/AttributeDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/BinOpDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/BinOpDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/BinOpDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/BreakDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/BreakDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/BreakDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/CallDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/CallDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/CallDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/CompareDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/CompareDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/CompareDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/ContinueDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ContinueDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/ContinueDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/DeleteDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/DeleteDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/DeleteDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/DictDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/DictDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/DictDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/ExecDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExecDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/ExecDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/ExprDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExprDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/ExprDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/ForDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ForDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/ForDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/GlobalDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/GlobalDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/GlobalDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/IfDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/IfDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/IfDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr=self_type.lookup("__getattr__"); - if (getattr!=null) { - if (py_name==null) { - py_name=PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError!=null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this,name); } public void __setattr__(String name,PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/IfExpDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/IfExpDerived.java 2009-10-07 02:48:36 UTC (rev 6844) +++ trunk/jython/src/org/python/antlr/ast/IfExpDerived.java 2009-10-07 02:50:46 UTC (rev 6845) @@ -981,43 +981,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type=getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute=self_type.lookup("__getattribute__"); - PyString py_name=null; - PyException firstAttributeError=null; - try { - if (getattribute!=null) { - py_name=PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); - PyObject ret=super.__findattr_ex__(name); - if (ret!=null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError=e; // saved to avoid swallowing ... [truncated message content] |
From: <pj...@us...> - 2009-10-07 02:48:55
|
Revision: 6844 http://jython.svn.sourceforge.net/jython/?rev=6844&view=rev Author: pjenvey Date: 2009-10-07 02:48:36 +0000 (Wed, 07 Oct 2009) Log Message: ----------- optimize attr lookup on Deriveds inheriting object.__getattribute__: don't bother going through the descriptor. Derived's __findattr_ex__ now lives in a Deriveds util class (like java.util.Arrays/Collections but trickier to pronounce) so it can toggle the package private fast path flag on PyType fixes #1102 Modified Paths: -------------- trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/templates/object.derived Added Paths: ----------- trunk/jython/src/org/python/core/Deriveds.java Added: trunk/jython/src/org/python/core/Deriveds.java =================================================================== --- trunk/jython/src/org/python/core/Deriveds.java (rev 0) +++ trunk/jython/src/org/python/core/Deriveds.java 2009-10-07 02:48:36 UTC (rev 6844) @@ -0,0 +1,63 @@ +/* Copyright (c) Jython Developers */ +package org.python.core; + +/** + * Derived classes utility methods. + */ +public class Deriveds { + + /** + * Derived's __findattr_ex__ implementation. + * + * This resides here (in org.python.core) because it manipulates PyType, and doesn't + * call any of the Derived classes' superclass methods. + */ + public static PyObject __findattr_ex__(PyObject self, String name) { + PyType type = self.getType(); + PyException firstAttributeError = null; + PyString pyName = null; + + try { + if (type.getUsesObjectGetattribute()) { + // Fast path: don't bother calling through the descriptor if using the + // generic __getattribute__ + PyObject result = self.object___findattr__(name); + if (result != null) { + return result; + } + // pass through to __getattr__ + } else { + PyObject getattribute = type.lookup("__getattribute__"); + if (getattribute == null) { + // This shouldn't happen + throw Py.SystemError(String.format("__getattribute__ not found on type %s", + type.getName())); + } + + if (getattribute == PyObject.objectGetattribute) { + type.setUsesObjectGetattribute(true); + } + pyName = PyString.fromInterned(name); + return getattribute.__get__(self, type).__call__(pyName); + } + } catch (PyException pye) { + if (!pye.match(Py.AttributeError)) { + throw pye; + } else { + // saved to avoid swallowing custom AttributeErrors, and pass through to + // __getattr__ + firstAttributeError = pye; + } + } + + PyObject getattr = type.lookup("__getattr__"); + if (getattr != null) { + return getattr.__get__(self, type).__call__(pyName != null + ? pyName : PyString.fromInterned(name)); + } + if (firstAttributeError != null) { + throw firstAttributeError; + } + return null; + } +} Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2009-10-06 20:32:55 UTC (rev 6843) +++ trunk/jython/src/org/python/core/PyObject.java 2009-10-07 02:48:36 UTC (rev 6844) @@ -38,6 +38,9 @@ /** Primitives classes their wrapper classes. */ private static final Map<Class<?>, Class<?>> primitiveMap = Generic.map(); + /** object.__getattribute__ descriptor, cached for use by Deriveds.__findattr_ex__. */ + static final PyObject objectGetattribute; + static { primitiveMap.put(Character.TYPE, Character.class); primitiveMap.put(Boolean.TYPE, Boolean.class); @@ -51,8 +54,9 @@ if (Py.BOOTSTRAP_TYPES.size() > 0) { Py.writeWarning("init", "Bootstrap types weren't encountered in bootstrapping: " + Py.BOOTSTRAP_TYPES); + } - } + objectGetattribute = TYPE.__findattr__("__getattribute__"); } public PyObject(PyType objtype) { @@ -3693,7 +3697,6 @@ // name must be interned final PyObject object___findattr__(String name) { - PyObject descr = objtype.lookup(name); PyObject res; @@ -3727,7 +3730,6 @@ final void object___setattr__(String name, PyObject value) { PyObject descr = objtype.lookup(name); - boolean set = false; if (descr != null) { @@ -3771,7 +3773,6 @@ final void object___delattr__(String name) { PyObject descr = objtype.lookup(name); - boolean delete = false; if (descr != null) { Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2009-10-06 20:32:55 UTC (rev 6843) +++ trunk/jython/src/org/python/core/PyType.java 2009-10-07 02:48:36 UTC (rev 6844) @@ -78,6 +78,9 @@ /** Whether finalization is required for this type's instances (implements __del__). */ private boolean needs_finalizer; + /** Whether this type's __getattribute__ is object.__getattribute__. */ + private volatile boolean usesObjectGetattribute; + /** The number of __slots__ defined. */ private int numSlots; @@ -685,6 +688,7 @@ mro = savedMro; throw t; } + postSetattr("__getattribute__"); } private void setIsBaseType(boolean isBaseType) { @@ -1329,6 +1333,12 @@ } }); } + } else if (name == "__getattribute__") { + traverse_hierarchy(false, new OnType() { + public boolean onType(PyType type) { + return (type.usesObjectGetattribute = false); + } + }); } } @@ -1381,6 +1391,12 @@ } }); } + } else if (name == "__getattribute__") { + traverse_hierarchy(false, new OnType() { + public boolean onType(PyType type) { + return (type.usesObjectGetattribute = false); + } + }); } } @@ -1480,6 +1496,14 @@ return doc; } + boolean getUsesObjectGetattribute() { + return usesObjectGetattribute; + } + + void setUsesObjectGetattribute(boolean usesObjectGetattribute) { + this.usesObjectGetattribute = usesObjectGetattribute; + } + public Object __tojava__(Class<?> c) { if (underlying_class != null && (c == Object.class || c == Class.class || c == Serializable.class)) { Modified: trunk/jython/src/templates/object.derived =================================================================== --- trunk/jython/src/templates/object.derived 2009-10-06 20:32:55 UTC (rev 6843) +++ trunk/jython/src/templates/object.derived 2009-10-07 02:48:36 UTC (rev 6844) @@ -314,44 +314,7 @@ } public PyObject __findattr_ex__(String name) { - PyType self_type = getType(); - // TODO: We should speed this up. As the __getattribute__ slot almost never - // changes, it is a good candidate for caching, as PyClass does with - // __getattr__. See #1102. - PyObject getattribute = self_type.lookup("__getattribute__"); - PyString py_name = null; - PyException firstAttributeError = null; - try { - if (getattribute != null) { - py_name = PyString.fromInterned(name); - return getattribute.__get__(this,self_type).__call__(py_name); - } else { - Py.Warning(String.format("__getattribute__ not found on type %s", - self_type.getName())); - PyObject ret = super.__findattr_ex__(name); - if (ret != null) { - return ret; - } // else: pass through to __getitem__ invocation - } - } catch (PyException e) { - if (!e.match(Py.AttributeError)) { - throw e; - } else { - firstAttributeError = e; // saved to avoid swallowing custom AttributeErrors - // and pass through to __getattr__ invocation. - } - } - PyObject getattr = self_type.lookup("__getattr__"); - if (getattr != null) { - if (py_name == null) { - py_name = PyString.fromInterned(name); - } - return getattr.__get__(this,self_type).__call__(py_name); - } - if (firstAttributeError != null) { - throw firstAttributeError; - } - return null; + return Deriveds.__findattr_ex__(this, name); } public void __setattr__(String name,PyObject value) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-06 20:33:08
|
Revision: 6843 http://jython.svn.sourceforge.net/jython/?rev=6843&view=rev Author: fwierzbicki Date: 2009-10-06 20:32:55 +0000 (Tue, 06 Oct 2009) Log Message: ----------- Make constants more.... constant in the compiler package. Changed confusing method names of the form Py*() that return constants to *constant. For example PyInteger() -> integerConstant(). Also reduced public interface of compiler package, especially around compiler constants. Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/compiler/Constant.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-06 13:11:06 UTC (rev 6842) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-06 20:32:55 UTC (rev 6843) @@ -434,7 +434,7 @@ scope.setup_closure(); scope.dump(); - module.PyCode(new Suite(node,node.getInternalBody()), name, true, + module.codeConstant(new Suite(node,node.getInternalBody()), name, true, className, false, false, node.getLine(), scope, cflags).get(code); @@ -2029,7 +2029,7 @@ scope.setup_closure(); scope.dump(); - module.PyCode(retSuite, name, true, className, + module.codeConstant(retSuite, name, true, className, false, false, node.getLine(), scope, cflags).get(code); if (!makeClosure(scope)) { @@ -2087,7 +2087,7 @@ scope.setup_closure(); scope.dump(); //Make code object out of suite - module.PyCode(new Suite(node,node.getInternalBody()), name, false, name, + module.codeConstant(new Suite(node,node.getInternalBody()), name, false, name, true, false, node.getLine(), scope, cflags).get(code); //Get doc string (if there) @@ -2114,13 +2114,13 @@ @Override public Object visitNum(Num node) throws Exception { if (node.getInternalN() instanceof PyInteger) { - module.PyInteger(((PyInteger) node.getInternalN()).getValue()).get(code); + module.integerConstant(((PyInteger) node.getInternalN()).getValue()).get(code); } else if (node.getInternalN() instanceof PyLong) { - module.PyLong(((PyObject)node.getInternalN()).__str__().toString()).get(code); + module.longConstant(((PyObject)node.getInternalN()).__str__().toString()).get(code); } else if (node.getInternalN() instanceof PyFloat) { - module.PyFloat(((PyFloat) node.getInternalN()).getValue()).get(code); + module.floatConstant(((PyFloat) node.getInternalN()).getValue()).get(code); } else if (node.getInternalN() instanceof PyComplex) { - module.PyComplex(((PyComplex) node.getInternalN()).imag).get(code); + module.complexConstant(((PyComplex) node.getInternalN()).imag).get(code); } return null; } @@ -2257,9 +2257,9 @@ public Object visitStr(Str node) throws Exception { PyString s = (PyString)node.getInternalS(); if (s instanceof PyUnicode) { - module.PyUnicode(s.asString()).get(code); + module.unicodeConstant(s.asString()).get(code); } else { - module.PyString(s.asString()).get(code); + module.stringConstant(s.asString()).get(code); } return null; } @@ -2304,7 +2304,7 @@ java.util.List<stmt> bod = new ArrayList<stmt>(); bod.add(n); - module.PyCode(new Suite(node, bod), "<genexpr>", true, + module.codeConstant(new Suite(node, bod), "<genexpr>", true, className, false, false, node.getLine(), scope, cflags).get(code); Modified: trunk/jython/src/org/python/compiler/Constant.java =================================================================== --- trunk/jython/src/org/python/compiler/Constant.java 2009-10-06 13:11:06 UTC (rev 6842) +++ trunk/jython/src/org/python/compiler/Constant.java 2009-10-06 20:32:55 UTC (rev 6843) @@ -7,11 +7,11 @@ import org.objectweb.asm.Opcodes; abstract class Constant implements Opcodes{ - public Module module; - public static int access = ACC_STATIC | ACC_FINAL; - public String name; + Module module; + static int access = ACC_STATIC | ACC_FINAL; + String name; - public abstract void get(Code mv) throws IOException; + abstract void get(Code mv) throws IOException; - public abstract void put(Code mv) throws IOException; + abstract void put(Code mv) throws IOException; } Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2009-10-06 13:11:06 UTC (rev 6842) +++ trunk/jython/src/org/python/compiler/Module.java 2009-10-06 20:32:55 UTC (rev 6843) @@ -38,19 +38,18 @@ import org.python.antlr.base.mod; import static org.python.util.CodegenUtils.*; -class PyIntegerConstant extends Constant implements ClassConstants, Opcodes -{ - int value; +class PyIntegerConstant extends Constant implements ClassConstants, Opcodes { + final int value; - public PyIntegerConstant(int value) { + PyIntegerConstant(int value) { this.value = value; } - public void get(Code c) throws IOException { + void get(Code c) throws IOException { c.getstatic(module.classfile.name, name, ci(PyInteger.class)); } - public void put(Code c) throws IOException { + void put(Code c) throws IOException { module.classfile.addField(name, ci(PyInteger.class), access); c.iconst(value); c.invokestatic(p(Py.class), "newInteger", sig(PyInteger.class, Integer.TYPE)); @@ -74,17 +73,17 @@ class PyFloatConstant extends Constant implements ClassConstants, Opcodes { - double value; + final double value; - public PyFloatConstant(double value) { + PyFloatConstant(double value) { this.value = value; } - public void get(Code c) throws IOException { + void get(Code c) throws IOException { c.getstatic(module.classfile.name, name, ci(PyFloat.class)); } - public void put(Code c) throws IOException { + void put(Code c) throws IOException { module.classfile.addField(name, ci(PyFloat.class), access); c.ldc(new Double(value)); c.invokestatic(p(Py.class), "newFloat", sig(PyFloat.class, Double.TYPE)); @@ -108,17 +107,17 @@ class PyComplexConstant extends Constant implements ClassConstants, Opcodes { - double value; + final double value; - public PyComplexConstant(double value) { + PyComplexConstant(double value) { this.value = value; } - public void get(Code c) throws IOException { + void get(Code c) throws IOException { c.getstatic(module.classfile.name, name, ci(PyComplex.class)); } - public void put(Code c) throws IOException { + void put(Code c) throws IOException { module.classfile.addField(name, ci(PyComplex.class), access); c.ldc(new Double(value)); c.invokestatic(p(Py.class), "newImaginary", sig(PyComplex.class, Double.TYPE)); @@ -142,17 +141,17 @@ class PyStringConstant extends Constant implements ClassConstants, Opcodes { - String value; + final String value; - public PyStringConstant(String value) { + PyStringConstant(String value) { this.value = value; } - public void get(Code c) throws IOException { + void get(Code c) throws IOException { c.getstatic(module.classfile.name, name, ci(PyString.class)); } - public void put(Code c) throws IOException { + void put(Code c) throws IOException { module.classfile.addField(name, ci(PyString.class), access); c.ldc(value); c.invokestatic(p(PyString.class), "fromInterned", sig(PyString.class, String.class)); @@ -176,17 +175,17 @@ class PyUnicodeConstant extends Constant implements ClassConstants, Opcodes { - String value; + final String value; - public PyUnicodeConstant(String value) { + PyUnicodeConstant(String value) { this.value = value; } - public void get(Code c) throws IOException { + void get(Code c) throws IOException { c.getstatic(module.classfile.name, name, ci(PyUnicode.class)); } - public void put(Code c) throws IOException { + void put(Code c) throws IOException { module.classfile.addField(name, ci(PyUnicode.class), access); c.ldc(value); c.invokestatic(p(PyUnicode.class), "fromInterned", sig(PyUnicode.class, String.class)); @@ -210,17 +209,17 @@ class PyLongConstant extends Constant implements ClassConstants, Opcodes { - String value; + final String value; - public PyLongConstant(String value) { + PyLongConstant(String value) { this.value = value; } - public void get(Code c) throws IOException { + void get(Code c) throws IOException { c.getstatic(module.classfile.name, name, ci(PyLong.class)); } - public void put(Code c) throws IOException { + void put(Code c) throws IOException { module.classfile.addField(name, ci(PyLong.class), access); c.ldc(value); c.invokestatic(p(Py.class), "newLong", sig(PyLong.class, String.class)); @@ -244,29 +243,29 @@ class PyCodeConstant extends Constant implements ClassConstants, Opcodes { - public String co_name; - public int argcount; - public List<String> names; - public int id; - public int co_firstlineno; - public boolean arglist, keywordlist; + String co_name; + int argcount; + List<String> names; + int id; + int co_firstlineno; + boolean arglist, keywordlist; String fname; // for nested scopes - public List<String> cellvars; - public List<String> freevars; - public int jy_npurecell; + List<String> cellvars; + List<String> freevars; + int jy_npurecell; - public int moreflags; + int moreflags; - public PyCodeConstant() { + PyCodeConstant() { } - public void get(Code c) throws IOException { + void get(Code c) throws IOException { c.getstatic(module.classfile.name, name, ci(PyCode.class)); } - public void put(Code c) throws IOException { + void put(Code c) throws IOException { module.classfile.addField(name, ci(PyCode.class), access); c.iconst(argcount); @@ -320,7 +319,7 @@ ClassFile classfile; Constant filename; String sfilename; - public Constant mainCode; + Constant mainCode; public boolean linenumbers; Future futures; Hashtable<PythonTree,ScopeInfo> scopes; @@ -338,7 +337,7 @@ constants = new Hashtable<Constant,Constant>(); sfilename = filename; if (filename != null) { - this.filename = PyString(filename); + this.filename = stringConstant(filename); } else { this.filename = null; } @@ -367,27 +366,27 @@ return ret; } - public Constant PyInteger(int value) { + Constant integerConstant(int value) { return findConstant(new PyIntegerConstant(value)); } - public Constant PyFloat(double value) { + Constant floatConstant(double value) { return findConstant(new PyFloatConstant(value)); } - public Constant PyComplex(double value) { + Constant complexConstant(double value) { return findConstant(new PyComplexConstant(value)); } - public Constant PyString(String value) { + Constant stringConstant(String value) { return findConstant(new PyStringConstant(value)); } - public Constant PyUnicode(String value) { + Constant unicodeConstant(String value) { return findConstant(new PyUnicodeConstant(value)); } - public Constant PyLong(String value) { + Constant longConstant(String value) { return findConstant(new PyLongConstant(value)); } @@ -420,20 +419,18 @@ return nameArray; } - private int to_cell; - - public PyCodeConstant PyCode(mod tree, String name, + PyCodeConstant codeConstant(mod tree, String name, boolean fast_locals, String className, boolean classBody, boolean printResults, int firstlineno, ScopeInfo scope) throws Exception { - return PyCode(tree,name,fast_locals,className,classBody, + return codeConstant(tree,name,fast_locals,className,classBody, printResults,firstlineno,scope,null); } - public PyCodeConstant PyCode(mod tree, String name, + PyCodeConstant codeConstant(mod tree, String name, boolean fast_locals, String className, boolean classBody, boolean printResults, int firstlineno, @@ -589,7 +586,7 @@ c.areturn(); } - public void addConstants(Code c) throws IOException { + void addConstants(Code c) throws IOException { classfile.addField("self", "L"+classfile.name+";", ACC_STATIC|ACC_FINAL); c.aload(0); c.putstatic(classfile.name, "self", "L"+classfile.name+";"); @@ -701,7 +698,7 @@ //Add __doc__ if it exists - Constant main = module.PyCode(node, "<module>", false, null, false, + Constant main = module.codeConstant(node, "<module>", false, null, false, printResults, 0, module.getScopeInfo(node), cflags); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <am...@us...> - 2009-10-06 13:11:16
|
Revision: 6842 http://jython.svn.sourceforge.net/jython/?rev=6842&view=rev Author: amak Date: 2009-10-06 13:11:06 +0000 (Tue, 06 Oct 2009) Log Message: ----------- Tabs to spaces, DOS line-endings to unix. Modified Paths: -------------- trunk/jython/Lib/modjy/__init__.py trunk/jython/Lib/modjy/modjy.py trunk/jython/Lib/modjy/modjy_exceptions.py trunk/jython/Lib/modjy/modjy_impl.py trunk/jython/Lib/modjy/modjy_log.py trunk/jython/Lib/modjy/modjy_params.py trunk/jython/Lib/modjy/modjy_publish.py trunk/jython/Lib/modjy/modjy_response.py trunk/jython/Lib/modjy/modjy_write.py trunk/jython/Lib/modjy/modjy_wsgi.py trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestContentHeaders.java trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestServletLifecycle.java trunk/jython/tests/modjy/test_apps_dir/content_header_tests.py trunk/jython/tests/modjy/test_apps_dir/environ_tests.py trunk/jython/tests/modjy/test_apps_dir/header_tests.py trunk/jython/tests/modjy/test_apps_dir/lifecycle_tests.py trunk/jython/tests/modjy/test_apps_dir/return_tests.py trunk/jython/tests/modjy/test_apps_dir/simple_app.py trunk/jython/tests/modjy/test_apps_dir/stream_tests.py trunk/jython/tests/modjy/test_apps_dir/web_inf_tests.py Modified: trunk/jython/Lib/modjy/__init__.py =================================================================== --- trunk/jython/Lib/modjy/__init__.py 2009-10-06 12:38:52 UTC (rev 6841) +++ trunk/jython/Lib/modjy/__init__.py 2009-10-06 13:11:06 UTC (rev 6842) @@ -1,22 +1,22 @@ -### -# -# Copyright Alan Kennedy. -# -# You may contact the copyright holder at this uri: -# -# http://www.xhaus.com/contact/modjy -# -# The licence under which this code is released is the Apache License v2.0. -# -# The terms and conditions of this license are listed in a file contained -# in the distribution that also contained this file, under the name -# LICENSE.txt. -# -# You may also read a copy of the license at the following web address. -# -# http://modjy.xhaus.com/LICENSE.txt -# -### - -__all__ = ['modjy', 'modjy_exceptions', 'modjy_impl', 'modjy_log', 'modjy_params', 'modjy_publish', 'modjy_response', 'modjy_write', 'modjy_wsgi',] - +### +# +# Copyright Alan Kennedy. +# +# You may contact the copyright holder at this uri: +# +# http://www.xhaus.com/contact/modjy +# +# The licence under which this code is released is the Apache License v2.0. +# +# The terms and conditions of this license are listed in a file contained +# in the distribution that also contained this file, under the name +# LICENSE.txt. +# +# You may also read a copy of the license at the following web address. +# +# http://modjy.xhaus.com/LICENSE.txt +# +### + +__all__ = ['modjy', 'modjy_exceptions', 'modjy_impl', 'modjy_log', 'modjy_params', 'modjy_publish', 'modjy_response', 'modjy_write', 'modjy_wsgi',] + Modified: trunk/jython/Lib/modjy/modjy.py =================================================================== --- trunk/jython/Lib/modjy/modjy.py 2009-10-06 12:38:52 UTC (rev 6841) +++ trunk/jython/Lib/modjy/modjy.py 2009-10-06 13:11:06 UTC (rev 6842) @@ -1,121 +1,121 @@ -### -# -# Copyright Alan Kennedy. -# -# You may contact the copyright holder at this uri: -# -# http://www.xhaus.com/contact/modjy -# -# The licence under which this code is released is the Apache License v2.0. -# -# The terms and conditions of this license are listed in a file contained -# in the distribution that also contained this file, under the name -# LICENSE.txt. -# -# You may also read a copy of the license at the following web address. -# -# http://modjy.xhaus.com/LICENSE.txt -# -### - -import jarray -import synchronize -import sys -import types - -sys.add_package("javax.servlet") -sys.add_package("javax.servlet.http") -sys.add_package("org.python.core") - -from modjy_exceptions import * -from modjy_log import * -from modjy_params import modjy_param_mgr, modjy_servlet_params -from modjy_wsgi import modjy_wsgi -from modjy_response import start_response_object -from modjy_impl import modjy_impl -from modjy_publish import modjy_publisher - -from javax.servlet.http import HttpServlet - -class modjy_servlet(HttpServlet, modjy_publisher, modjy_wsgi, modjy_impl): - - def __init__(self): - HttpServlet.__init__(self) - - def do_param(self, name, value): - if name[:3] == 'log': - getattr(self.log, "set_%s" % name)(value) - else: - self.params[name] = value - - def process_param_container(self, param_container): - param_enum = param_container.getInitParameterNames() - while param_enum.hasMoreElements(): - param_name = param_enum.nextElement() - self.do_param(param_name, param_container.getInitParameter(param_name)) - - def get_params(self): - self.process_param_container(self.servlet_context) - self.process_param_container(self.servlet) - - def init(self, delegator): - self.servlet = delegator - self.servlet_context = self.servlet.getServletContext() - self.servlet_config = self.servlet.getServletConfig() - self.log = modjy_logger(self.servlet_context) - self.params = modjy_param_mgr(modjy_servlet_params) - self.get_params() - self.init_impl() - self.init_publisher() - import modjy_exceptions - self.exc_handler = getattr(modjy_exceptions, '%s_handler' % self.params['exc_handler'])() - - def service (self, req, resp): - wsgi_environ = {} - try: - self.dispatch_to_application(req, resp, wsgi_environ) - except ModjyException, mx: - self.log.error("Exception servicing request: %s" % str(mx)) - typ, value, tb = sys.exc_info()[:] - self.exc_handler.handle(req, resp, wsgi_environ, mx, (typ, value, tb) ) - - def get_j2ee_ns(self, req, resp): - return { - 'servlet': self.servlet, - 'servlet_context': self.servlet_context, - 'servlet_config': self.servlet_config, - 'request': req, - 'response': resp, - } - - def dispatch_to_application(self, req, resp, environ): - app_callable = self.get_app_object(req, environ) - self.set_wsgi_environment(req, resp, environ, self.params, self.get_j2ee_ns(req, resp)) - response_callable = start_response_object(req, resp) - try: - app_return = self.call_application(app_callable, environ, response_callable) - if app_return is None: - raise ReturnNotIterable("Application returned None: must return an iterable") - self.deal_with_app_return(environ, response_callable, app_return) - except ModjyException, mx: - self.raise_exc(mx.__class__, str(mx)) - except Exception, x: - self.raise_exc(ApplicationException, str(x)) - - def call_application(self, app_callable, environ, response_callable): - if self.params['multithread']: - return app_callable.__call__(environ, response_callable) - else: - return synchronize.apply_synchronized( \ - app_callable, \ - app_callable, \ - (environ, response_callable)) - - def expand_relative_path(self, path): - if path.startswith("$"): - return self.servlet.getServletContext().getRealPath(path[1:]) - return path - - def raise_exc(self, exc_class, message): - self.log.error(message) - raise exc_class(message) +### +# +# Copyright Alan Kennedy. +# +# You may contact the copyright holder at this uri: +# +# http://www.xhaus.com/contact/modjy +# +# The licence under which this code is released is the Apache License v2.0. +# +# The terms and conditions of this license are listed in a file contained +# in the distribution that also contained this file, under the name +# LICENSE.txt. +# +# You may also read a copy of the license at the following web address. +# +# http://modjy.xhaus.com/LICENSE.txt +# +### + +import jarray +import synchronize +import sys +import types + +sys.add_package("javax.servlet") +sys.add_package("javax.servlet.http") +sys.add_package("org.python.core") + +from modjy_exceptions import * +from modjy_log import * +from modjy_params import modjy_param_mgr, modjy_servlet_params +from modjy_wsgi import modjy_wsgi +from modjy_response import start_response_object +from modjy_impl import modjy_impl +from modjy_publish import modjy_publisher + +from javax.servlet.http import HttpServlet + +class modjy_servlet(HttpServlet, modjy_publisher, modjy_wsgi, modjy_impl): + + def __init__(self): + HttpServlet.__init__(self) + + def do_param(self, name, value): + if name[:3] == 'log': + getattr(self.log, "set_%s" % name)(value) + else: + self.params[name] = value + + def process_param_container(self, param_container): + param_enum = param_container.getInitParameterNames() + while param_enum.hasMoreElements(): + param_name = param_enum.nextElement() + self.do_param(param_name, param_container.getInitParameter(param_name)) + + def get_params(self): + self.process_param_container(self.servlet_context) + self.process_param_container(self.servlet) + + def init(self, delegator): + self.servlet = delegator + self.servlet_context = self.servlet.getServletContext() + self.servlet_config = self.servlet.getServletConfig() + self.log = modjy_logger(self.servlet_context) + self.params = modjy_param_mgr(modjy_servlet_params) + self.get_params() + self.init_impl() + self.init_publisher() + import modjy_exceptions + self.exc_handler = getattr(modjy_exceptions, '%s_handler' % self.params['exc_handler'])() + + def service (self, req, resp): + wsgi_environ = {} + try: + self.dispatch_to_application(req, resp, wsgi_environ) + except ModjyException, mx: + self.log.error("Exception servicing request: %s" % str(mx)) + typ, value, tb = sys.exc_info()[:] + self.exc_handler.handle(req, resp, wsgi_environ, mx, (typ, value, tb) ) + + def get_j2ee_ns(self, req, resp): + return { + 'servlet': self.servlet, + 'servlet_context': self.servlet_context, + 'servlet_config': self.servlet_config, + 'request': req, + 'response': resp, + } + + def dispatch_to_application(self, req, resp, environ): + app_callable = self.get_app_object(req, environ) + self.set_wsgi_environment(req, resp, environ, self.params, self.get_j2ee_ns(req, resp)) + response_callable = start_response_object(req, resp) + try: + app_return = self.call_application(app_callable, environ, response_callable) + if app_return is None: + raise ReturnNotIterable("Application returned None: must return an iterable") + self.deal_with_app_return(environ, response_callable, app_return) + except ModjyException, mx: + self.raise_exc(mx.__class__, str(mx)) + except Exception, x: + self.raise_exc(ApplicationException, str(x)) + + def call_application(self, app_callable, environ, response_callable): + if self.params['multithread']: + return app_callable.__call__(environ, response_callable) + else: + return synchronize.apply_synchronized( \ + app_callable, \ + app_callable, \ + (environ, response_callable)) + + def expand_relative_path(self, path): + if path.startswith("$"): + return self.servlet.getServletContext().getRealPath(path[1:]) + return path + + def raise_exc(self, exc_class, message): + self.log.error(message) + raise exc_class(message) Modified: trunk/jython/Lib/modjy/modjy_exceptions.py =================================================================== --- trunk/jython/Lib/modjy/modjy_exceptions.py 2009-10-06 12:38:52 UTC (rev 6841) +++ trunk/jython/Lib/modjy/modjy_exceptions.py 2009-10-06 13:11:06 UTC (rev 6842) @@ -1,91 +1,91 @@ -### -# -# Copyright Alan Kennedy. -# -# You may contact the copyright holder at this uri: -# -# http://www.xhaus.com/contact/modjy -# -# The licence under which this code is released is the Apache License v2.0. -# -# The terms and conditions of this license are listed in a file contained -# in the distribution that also contained this file, under the name -# LICENSE.txt. -# -# You may also read a copy of the license at the following web address. -# -# http://modjy.xhaus.com/LICENSE.txt -# -### - -import sys -import StringIO -import traceback - -from java.lang import IllegalStateException -from java.io import IOException -from javax.servlet import ServletException - -class ModjyException(Exception): pass - -class ModjyIOException(ModjyException): pass - -class ConfigException(ModjyException): pass -class BadParameter(ConfigException): pass -class ApplicationNotFound(ConfigException): pass -class NoCallable(ConfigException): pass - -class RequestException(ModjyException): pass - -class ApplicationException(ModjyException): pass -class StartResponseNotCalled(ApplicationException): pass -class StartResponseCalledTwice(ApplicationException): pass -class ResponseCommitted(ApplicationException): pass -class HopByHopHeaderSet(ApplicationException): pass -class WrongLength(ApplicationException): pass -class BadArgument(ApplicationException): pass -class ReturnNotIterable(ApplicationException): pass -class NonStringOutput(ApplicationException): pass - -class exception_handler: - - def handle(self, req, resp, environ, exc, exc_info): - pass - - def get_status_and_message(self, req, resp, exc): - return resp.SC_INTERNAL_SERVER_ERROR, "Server configuration error" - -# -# Special exception handler for testing -# - -class testing_handler(exception_handler): - - def handle(self, req, resp, environ, exc, exc_info): - typ, value, tb = exc_info - err_msg = StringIO.StringIO() - err_msg.write("%s: %s\n" % (typ, value,) ) - err_msg.write(">Environment\n") - for k in environ.keys(): - err_msg.write("%s=%s\n" % (k, repr(environ[k])) ) - err_msg.write("<Environment\n") - err_msg.write(">TraceBack\n") - for line in traceback.format_exception(typ, value, tb): - err_msg.write(line) - err_msg.write("<TraceBack\n") - try: - status, message = self.get_status_and_message(req, resp, exc) - resp.setStatus(status) - resp.setContentLength(len(err_msg.getvalue())) - resp.getOutputStream().write(err_msg.getvalue()) - except IllegalStateException, ise: - raise exc # Let the container deal with it - -# -# Standard exception handler -# - -class standard_handler(exception_handler): - - def handle(self, req, resp, environ, exc, exc_info): - raise exc_info[0], exc_info[1], exc_info[2] +### +# +# Copyright Alan Kennedy. +# +# You may contact the copyright holder at this uri: +# +# http://www.xhaus.com/contact/modjy +# +# The licence under which this code is released is the Apache License v2.0. +# +# The terms and conditions of this license are listed in a file contained +# in the distribution that also contained this file, under the name +# LICENSE.txt. +# +# You may also read a copy of the license at the following web address. +# +# http://modjy.xhaus.com/LICENSE.txt +# +### + +import sys +import StringIO +import traceback + +from java.lang import IllegalStateException +from java.io import IOException +from javax.servlet import ServletException + +class ModjyException(Exception): pass + +class ModjyIOException(ModjyException): pass + +class ConfigException(ModjyException): pass +class BadParameter(ConfigException): pass +class ApplicationNotFound(ConfigException): pass +class NoCallable(ConfigException): pass + +class RequestException(ModjyException): pass + +class ApplicationException(ModjyException): pass +class StartResponseNotCalled(ApplicationException): pass +class StartResponseCalledTwice(ApplicationException): pass +class ResponseCommitted(ApplicationException): pass +class HopByHopHeaderSet(ApplicationException): pass +class WrongLength(ApplicationException): pass +class BadArgument(ApplicationException): pass +class ReturnNotIterable(ApplicationException): pass +class NonStringOutput(ApplicationException): pass + +class exception_handler: + + def handle(self, req, resp, environ, exc, exc_info): + pass + + def get_status_and_message(self, req, resp, exc): + return resp.SC_INTERNAL_SERVER_ERROR, "Server configuration error" + +# +# Special exception handler for testing +# + +class testing_handler(exception_handler): + + def handle(self, req, resp, environ, exc, exc_info): + typ, value, tb = exc_info + err_msg = StringIO.StringIO() + err_msg.write("%s: %s\n" % (typ, value,) ) + err_msg.write(">Environment\n") + for k in environ.keys(): + err_msg.write("%s=%s\n" % (k, repr(environ[k])) ) + err_msg.write("<Environment\n") + err_msg.write(">TraceBack\n") + for line in traceback.format_exception(typ, value, tb): + err_msg.write(line) + err_msg.write("<TraceBack\n") + try: + status, message = self.get_status_and_message(req, resp, exc) + resp.setStatus(status) + resp.setContentLength(len(err_msg.getvalue())) + resp.getOutputStream().write(err_msg.getvalue()) + except IllegalStateException, ise: + raise exc # Let the container deal with it + +# +# Standard exception handler +# + +class standard_handler(exception_handler): + + def handle(self, req, resp, environ, exc, exc_info): + raise exc_info[0], exc_info[1], exc_info[2] Modified: trunk/jython/Lib/modjy/modjy_impl.py =================================================================== --- trunk/jython/Lib/modjy/modjy_impl.py 2009-10-06 12:38:52 UTC (rev 6841) +++ trunk/jython/Lib/modjy/modjy_impl.py 2009-10-06 13:11:06 UTC (rev 6842) @@ -1,101 +1,101 @@ -### -# -# Copyright Alan Kennedy. -# -# You may contact the copyright holder at this uri: -# -# http://www.xhaus.com/contact/modjy -# -# The licence under which this code is released is the Apache License v2.0. -# -# The terms and conditions of this license are listed in a file contained -# in the distribution that also contained this file, under the name -# LICENSE.txt. -# -# You may also read a copy of the license at the following web address. -# -# http://modjy.xhaus.com/LICENSE.txt -# -### - -import types -import sys - -from modjy_exceptions import * - -class modjy_impl: - - def deal_with_app_return(self, environ, start_response_callable, app_return): - self.log.debug("Processing app return type: %s" % str(type(app_return))) - if isinstance(app_return, types.StringTypes): - raise ReturnNotIterable("Application returned object that was not an iterable: %s" % str(type(app_return))) - if type(app_return) is types.FileType: - pass # TBD: What to do here? can't call fileno() - if hasattr(app_return, '__len__') and callable(app_return.__len__): - expected_pieces = app_return.__len__() - else: - expected_pieces = -1 - try: - try: - ix = 0 - for next_piece in app_return: - if not isinstance(next_piece, types.StringTypes): - raise NonStringOutput("Application returned iterable containing non-strings: %s" % str(type(next_piece))) - if ix == 0: - # The application may have called start_response in the first iteration - if not start_response_callable.called: - raise StartResponseNotCalled("Start_response callable was never called.") - if not start_response_callable.content_length \ - and expected_pieces == 1 \ - and start_response_callable.write_callable.num_writes == 0: - # Take the length of the first piece - start_response_callable.set_content_length(len(next_piece)) - start_response_callable.write_callable(next_piece) - ix += 1 - if ix == expected_pieces: - break - if expected_pieces != -1 and ix != expected_pieces: - raise WrongLength("Iterator len() was wrong. Expected %d pieces: got %d" % (expected_pieces, ix) ) - except AttributeError, ax: - if str(ax) == "__getitem__": - raise ReturnNotIterable("Application returned object that was not an iterable: %s" % str(type(app_return))) - else: - raise ax - except TypeError, tx: - raise ReturnNotIterable("Application returned object that was not an iterable: %s" % str(type(app_return))) - except ModjyException, mx: - raise mx - except Exception, x: - raise ApplicationException(x) - finally: - if hasattr(app_return, 'close') and callable(app_return.close): - app_return.close() - - def init_impl(self): - self.do_j_env_params() - - def add_packages(self, package_list): - packages = [p.strip() for p in package_list.split(';')] - for p in packages: - self.log.info("Adding java package %s to jython" % p) - sys.add_package(p) - - def add_classdirs(self, classdir_list): - classdirs = [cd.strip() for cd in classdir_list.split(';')] - for cd in classdirs: - self.log.info("Adding directory %s to jython class file search path" % cd) - sys.add_classdir(cd) - - def add_extdirs(self, extdir_list): - extdirs = [ed.strip() for ed in extdir_list.split(';')] - for ed in extdirs: - self.log.info("Adding directory %s for .jars and .zips search path" % ed) - sys.add_extdir(self.expand_relative_path(ed)) - - def do_j_env_params(self): - if self.params['packages']: - self.add_packages(self.params['packages']) - if self.params['classdirs']: - self.add_classdirs(self.params['classdirs']) - if self.params['extdirs']: - self.add_extdirs(self.params['extdirs']) +### +# +# Copyright Alan Kennedy. +# +# You may contact the copyright holder at this uri: +# +# http://www.xhaus.com/contact/modjy +# +# The licence under which this code is released is the Apache License v2.0. +# +# The terms and conditions of this license are listed in a file contained +# in the distribution that also contained this file, under the name +# LICENSE.txt. +# +# You may also read a copy of the license at the following web address. +# +# http://modjy.xhaus.com/LICENSE.txt +# +### + +import types +import sys + +from modjy_exceptions import * + +class modjy_impl: + + def deal_with_app_return(self, environ, start_response_callable, app_return): + self.log.debug("Processing app return type: %s" % str(type(app_return))) + if isinstance(app_return, types.StringTypes): + raise ReturnNotIterable("Application returned object that was not an iterable: %s" % str(type(app_return))) + if type(app_return) is types.FileType: + pass # TBD: What to do here? can't call fileno() + if hasattr(app_return, '__len__') and callable(app_return.__len__): + expected_pieces = app_return.__len__() + else: + expected_pieces = -1 + try: + try: + ix = 0 + for next_piece in app_return: + if not isinstance(next_piece, types.StringTypes): + raise NonStringOutput("Application returned iterable containing non-strings: %s" % str(type(next_piece))) + if ix == 0: + # The application may have called start_response in the first iteration + if not start_response_callable.called: + raise StartResponseNotCalled("Start_response callable was never called.") + if not start_response_callable.content_length \ + and expected_pieces == 1 \ + and start_response_callable.write_callable.num_writes == 0: + # Take the length of the first piece + start_response_callable.set_content_length(len(next_piece)) + start_response_callable.write_callable(next_piece) + ix += 1 + if ix == expected_pieces: + break + if expected_pieces != -1 and ix != expected_pieces: + raise WrongLength("Iterator len() was wrong. Expected %d pieces: got %d" % (expected_pieces, ix) ) + except AttributeError, ax: + if str(ax) == "__getitem__": + raise ReturnNotIterable("Application returned object that was not an iterable: %s" % str(type(app_return))) + else: + raise ax + except TypeError, tx: + raise ReturnNotIterable("Application returned object that was not an iterable: %s" % str(type(app_return))) + except ModjyException, mx: + raise mx + except Exception, x: + raise ApplicationException(x) + finally: + if hasattr(app_return, 'close') and callable(app_return.close): + app_return.close() + + def init_impl(self): + self.do_j_env_params() + + def add_packages(self, package_list): + packages = [p.strip() for p in package_list.split(';')] + for p in packages: + self.log.info("Adding java package %s to jython" % p) + sys.add_package(p) + + def add_classdirs(self, classdir_list): + classdirs = [cd.strip() for cd in classdir_list.split(';')] + for cd in classdirs: + self.log.info("Adding directory %s to jython class file search path" % cd) + sys.add_classdir(cd) + + def add_extdirs(self, extdir_list): + extdirs = [ed.strip() for ed in extdir_list.split(';')] + for ed in extdirs: + self.log.info("Adding directory %s for .jars and .zips search path" % ed) + sys.add_extdir(self.expand_relative_path(ed)) + + def do_j_env_params(self): + if self.params['packages']: + self.add_packages(self.params['packages']) + if self.params['classdirs']: + self.add_classdirs(self.params['classdirs']) + if self.params['extdirs']: + self.add_extdirs(self.params['extdirs']) Modified: trunk/jython/Lib/modjy/modjy_log.py =================================================================== --- trunk/jython/Lib/modjy/modjy_log.py 2009-10-06 12:38:52 UTC (rev 6841) +++ trunk/jython/Lib/modjy/modjy_log.py 2009-10-06 13:11:06 UTC (rev 6842) @@ -1,80 +1,80 @@ -### -# -# Copyright Alan Kennedy. -# -# You may contact the copyright holder at this uri: -# -# http://www.xhaus.com/contact/modjy -# -# The licence under which this code is released is the Apache License v2.0. -# -# The terms and conditions of this license are listed in a file contained -# in the distribution that also contained this file, under the name -# LICENSE.txt. -# -# You may also read a copy of the license at the following web address. -# -# http://modjy.xhaus.com/LICENSE.txt -# -### - -import java - -import sys - -DEBUG = 'debug' -INFO = 'info' -WARN = 'warn' -ERROR = 'error' -FATAL = 'fatal' - -levels_dict = {} -ix = 0 -for level in [DEBUG, INFO, WARN, ERROR, FATAL, ]: - levels_dict[level]=ix - ix += 1 - -class modjy_logger: - - def __init__(self, context): - self.log_ctx = context - self.format_str = "%(lvl)s:\t%(msg)s" - self.log_level = levels_dict[DEBUG] - - def _log(self, level, level_str, msg, exc): - if level >= self.log_level: - msg = self.format_str % {'lvl': level_str, 'msg': msg, } - if exc: -# java.lang.System.err.println(msg, exc) - self.log_ctx.log(msg, exc) - else: -# java.lang.System.err.println(msg) - self.log_ctx.log(msg) - - def debug(self, msg, exc=None): - self._log(0, DEBUG, msg, exc) - - def info(self, msg, exc=None): - self._log(1, INFO, msg, exc) - - def warn(self, msg, exc=None): - self._log(2, WARN, msg, exc) - - def error(self, msg, exc=None): - self._log(3, ERROR, msg, exc) - - def fatal(self, msg, exc=None): - self._log(4, FATAL, msg, exc) - - def set_log_level(self, level_string): - try: - self.log_level = levels_dict[level_string] - except KeyError: - raise BadParameter("Invalid log level: '%s'" % level_string) - - def set_log_format(self, format_string): - # BUG! Format string never actually used in this function. - try: - self._log(debug, "This is a log formatting test", None) - except KeyError: - raise BadParameter("Bad format string: '%s'" % format_string) +### +# +# Copyright Alan Kennedy. +# +# You may contact the copyright holder at this uri: +# +# http://www.xhaus.com/contact/modjy +# +# The licence under which this code is released is the Apache License v2.0. +# +# The terms and conditions of this license are listed in a file contained +# in the distribution that also contained this file, under the name +# LICENSE.txt. +# +# You may also read a copy of the license at the following web address. +# +# http://modjy.xhaus.com/LICENSE.txt +# +### + +import java + +import sys + +DEBUG = 'debug' +INFO = 'info' +WARN = 'warn' +ERROR = 'error' +FATAL = 'fatal' + +levels_dict = {} +ix = 0 +for level in [DEBUG, INFO, WARN, ERROR, FATAL, ]: + levels_dict[level]=ix + ix += 1 + +class modjy_logger: + + def __init__(self, context): + self.log_ctx = context + self.format_str = "%(lvl)s:\t%(msg)s" + self.log_level = levels_dict[DEBUG] + + def _log(self, level, level_str, msg, exc): + if level >= self.log_level: + msg = self.format_str % {'lvl': level_str, 'msg': msg, } + if exc: +# java.lang.System.err.println(msg, exc) + self.log_ctx.log(msg, exc) + else: +# java.lang.System.err.println(msg) + self.log_ctx.log(msg) + + def debug(self, msg, exc=None): + self._log(0, DEBUG, msg, exc) + + def info(self, msg, exc=None): + self._log(1, INFO, msg, exc) + + def warn(self, msg, exc=None): + self._log(2, WARN, msg, exc) + + def error(self, msg, exc=None): + self._log(3, ERROR, msg, exc) + + def fatal(self, msg, exc=None): + self._log(4, FATAL, msg, exc) + + def set_log_level(self, level_string): + try: + self.log_level = levels_dict[level_string] + except KeyError: + raise BadParameter("Invalid log level: '%s'" % level_string) + + def set_log_format(self, format_string): + # BUG! Format string never actually used in this function. + try: + self._log(debug, "This is a log formatting test", None) + except KeyError: + raise BadParameter("Bad format string: '%s'" % format_string) Modified: trunk/jython/Lib/modjy/modjy_params.py =================================================================== --- trunk/jython/Lib/modjy/modjy_params.py 2009-10-06 12:38:52 UTC (rev 6841) +++ trunk/jython/Lib/modjy/modjy_params.py 2009-10-06 13:11:06 UTC (rev 6842) @@ -1,84 +1,84 @@ -### -# -# Copyright Alan Kennedy. -# -# You may contact the copyright holder at this uri: -# -# http://www.xhaus.com/contact/modjy -# -# The licence under which this code is released is the Apache License v2.0. -# -# The terms and conditions of this license are listed in a file contained -# in the distribution that also contained this file, under the name -# LICENSE.txt. -# -# You may also read a copy of the license at the following web address. -# -# http://modjy.xhaus.com/LICENSE.txt -# -### - -from UserDict import UserDict - -BOOLEAN = ('boolean', int) -INTEGER = ('integer', int) -FLOAT = ('float', float) -STRING = ('string', None) - -modjy_servlet_params = { - - 'multithread': (BOOLEAN, 1), - 'cache_callables': (BOOLEAN, 1), - 'reload_on_mod': (BOOLEAN, 0), - - 'app_import_name': (STRING, None), - - 'app_directory': (STRING, None), - 'app_filename': (STRING, 'application.py'), - 'app_callable_name': (STRING, 'handler'), - 'callable_query_name': (STRING, None), - - 'exc_handler': (STRING, 'standard'), - - 'log_level': (STRING, 'info'), - - 'packages': (STRING, None), - 'classdirs': (STRING, None), - 'extdirs': (STRING, None), - - 'initial_env': (STRING, None), -} - -class modjy_param_mgr(UserDict): - - def __init__(self, param_types): - UserDict.__init__(self) - self.param_types = param_types - for pname in self.param_types.keys(): - typ, default = self.param_types[pname] - self.__setitem__(pname, default) - - def __getitem__(self, name): - return self._get_defaulted_value(name) - - def __setitem__(self, name, value): - self.data[name] = self._convert_value(name, value) - - def _convert_value(self, name, value): - if self.param_types.has_key(name): - typ, default = self.param_types[name] - typ_str, typ_func = typ - if typ_func: - try: - return typ_func(value) - except ValueError: - raise BadParameter("Illegal value for %s parameter '%s': %s" % (typ_str, name, value) ) - return value - - def _get_defaulted_value(self, name): - if self.data.has_key(name): - return self.data[name] - if self.param_types.has_key(name): - typ, default = self.param_types[name] - return default - raise KeyError(name) +### +# +# Copyright Alan Kennedy. +# +# You may contact the copyright holder at this uri: +# +# http://www.xhaus.com/contact/modjy +# +# The licence under which this code is released is the Apache License v2.0. +# +# The terms and conditions of this license are listed in a file contained +# in the distribution that also contained this file, under the name +# LICENSE.txt. +# +# You may also read a copy of the license at the following web address. +# +# http://modjy.xhaus.com/LICENSE.txt +# +### + +from UserDict import UserDict + +BOOLEAN = ('boolean', int) +INTEGER = ('integer', int) +FLOAT = ('float', float) +STRING = ('string', None) + +modjy_servlet_params = { + + 'multithread': (BOOLEAN, 1), + 'cache_callables': (BOOLEAN, 1), + 'reload_on_mod': (BOOLEAN, 0), + + 'app_import_name': (STRING, None), + + 'app_directory': (STRING, None), + 'app_filename': (STRING, 'application.py'), + 'app_callable_name': (STRING, 'handler'), + 'callable_query_name': (STRING, None), + + 'exc_handler': (STRING, 'standard'), + + 'log_level': (STRING, 'info'), + + 'packages': (STRING, None), + 'classdirs': (STRING, None), + 'extdirs': (STRING, None), + + 'initial_env': (STRING, None), +} + +class modjy_param_mgr(UserDict): + + def __init__(self, param_types): + UserDict.__init__(self) + self.param_types = param_types + for pname in self.param_types.keys(): + typ, default = self.param_types[pname] + self.__setitem__(pname, default) + + def __getitem__(self, name): + return self._get_defaulted_value(name) + + def __setitem__(self, name, value): + self.data[name] = self._convert_value(name, value) + + def _convert_value(self, name, value): + if self.param_types.has_key(name): + typ, default = self.param_types[name] + typ_str, typ_func = typ + if typ_func: + try: + return typ_func(value) + except ValueError: + raise BadParameter("Illegal value for %s parameter '%s': %s" % (typ_str, name, value) ) + return value + + def _get_defaulted_value(self, name): + if self.data.has_key(name): + return self.data[name] + if self.param_types.has_key(name): + typ, default = self.param_types[name] + return default + raise KeyError(name) Modified: trunk/jython/Lib/modjy/modjy_publish.py =================================================================== --- trunk/jython/Lib/modjy/modjy_publish.py 2009-10-06 12:38:52 UTC (rev 6841) +++ trunk/jython/Lib/modjy/modjy_publish.py 2009-10-06 13:11:06 UTC (rev 6842) @@ -1,138 +1,138 @@ -### -# -# Copyright Alan Kennedy. -# -# You may contact the copyright holder at this uri: -# -# http://www.xhaus.com/contact/modjy -# -# The licence under which this code is released is the Apache License v2.0. -# -# The terms and conditions of this license are listed in a file contained -# in the distribution that also contained this file, under the name -# LICENSE.txt. -# -# You may also read a copy of the license at the following web address. -# -# http://modjy.xhaus.com/LICENSE.txt -# -### - -import sys -import synchronize - -from java.io import File - -from modjy_exceptions import * - -class modjy_publisher: - - def init_publisher(self): - self.cache = None - if self.params['app_directory']: - self.app_directory = self.expand_relative_path(self.params['app_directory']) - else: - self.app_directory = self.servlet_context.getRealPath('/') - self.params['app_directory'] = self.app_directory - if not self.app_directory in sys.path: - sys.path.append(self.app_directory) - - def map_uri(self, req, environ): - source_uri = '%s%s%s' % (self.app_directory, File.separator, self.params['app_filename']) - callable_name = self.params['app_callable_name'] - if self.params['callable_query_name']: - query_string = req.getQueryString() - if query_string and '=' in query_string: - for name_val in query_string.split('&'): - name, value = name_val.split('=') - if name == self.params['callable_query_name']: - callable_name = value - return source_uri, callable_name - - def get_app_object(self, req, environ): - environ["SCRIPT_NAME"] = "%s%s" % (req.getContextPath(), req.getServletPath()) - path_info = req.getPathInfo() or "" - environ["PATH_INFO"] = path_info - environ["PATH_TRANSLATED"] = File(self.app_directory, path_info).getPath() - - if self.params['app_import_name'] is not None: - return self.get_app_object_importable(self.params['app_import_name']) - else: - if self.cache is None: - self.cache = {} - return self.get_app_object_old_style(req, environ) - - get_app_object = synchronize.make_synchronized(get_app_object) - - def get_app_object_importable(self, importable_name): - self.log.debug("Attempting to import application callable '%s'\n" % (importable_name, )) - # Under the importable mechanism, the cache contains a single object - if self.cache is None: - application, instantiable, method_name = self.load_importable(importable_name.strip()) - if instantiable and self.params['cache_callables']: - application = application() - self.cache = application, instantiable, method_name - application, instantiable, method_name = self.cache - self.log.debug("Application is " + str(application)) - if instantiable and not self.params['cache_callables']: - application = application() - self.log.debug("Instantiated application is " + str(application)) - if method_name is not None: - if not hasattr(application, method_name): - self.log.fatal("Attribute error application callable '%s' as no method '%s'" % (application, method_name)) - self.raise_exc(ApplicationNotFound, "Attribute error application callable '%s' as no method '%s'" % (application, method_name)) - application = getattr(application, method_name) - self.log.debug("Application method is " + str(application)) - return application - - def load_importable(self, name): - try: - instantiable = False ; method_name = None - importable_name = name - if name.find('()') != -1: - instantiable = True - importable_name, method_name = name.split('()') - if method_name.startswith('.'): - method_name = method_name[1:] - if not method_name: - method_name = None - module_path, from_name = importable_name.rsplit('.', 1) - imported = __import__(module_path, globals(), locals(), [from_name]) - imported = getattr(imported, from_name) - return imported, instantiable, method_name - except (ImportError, AttributeError), aix: - self.log.fatal("Import error import application callable '%s': %s\n" % (name, str(aix))) - self.raise_exc(ApplicationNotFound, "Failed to import app callable '%s': %s" % (name, str(aix))) - - def get_app_object_old_style(self, req, environ): - source_uri, callable_name = self.map_uri(req, environ) - source_filename = source_uri - if not self.params['cache_callables']: - self.log.debug("Caching of callables disabled") - return self.load_object(source_filename, callable_name) - if not self.cache.has_key( (source_filename, callable_name) ): - self.log.debug("Callable object not in cache: %s#%s" % (source_filename, callable_name) ) - return self.load_object(source_filename, callable_name) - app_callable, last_mod = self.cache.get( (source_filename, callable_name) ) - self.log.debug("Callable object was in cache: %s#%s" % (source_filename, callable_name) ) - if self.params['reload_on_mod']: - f = File(source_filename) - if f.lastModified() > last_mod: - self.log.info("Source file '%s' has been modified: reloading" % source_filename) - return self.load_object(source_filename, callable_name) - return app_callable - - def load_object(self, path, callable_name): - try: - app_ns = {} ; execfile(path, app_ns) - app_callable = app_ns[callable_name] - f = File(path) - self.cache[ (path, callable_name) ] = (app_callable, f.lastModified()) - return app_callable - except IOError, ioe: - self.raise_exc(ApplicationNotFound, "Application filename not found: %s" % path) - except KeyError, k: - self.raise_exc(NoCallable, "No callable named '%s' in %s" % (callable_name, path)) - except Exception, x: - self.raise_exc(NoCallable, "Error loading jython callable '%s': %s" % (callable_name, str(x)) ) - +### +# +# Copyright Alan Kennedy. +# +# You may contact the copyright holder at this uri: +# +# http://www.xhaus.com/contact/modjy +# +# The licence under which this code is released is the Apache License v2.0. +# +# The terms and conditions of this license are listed in a file contained +# in the distribution that also contained this file, under the name +# LICENSE.txt. +# +# You may also read a copy of the license at the following web address. +# +# http://modjy.xhaus.com/LICENSE.txt +# +### + +import sys +import synchronize + +from java.io import File + +from modjy_exceptions import * + +class modjy_publisher: + + def init_publisher(self): + self.cache = None + if self.params['app_directory']: + self.app_directory = self.expand_relative_path(self.params['app_directory']) + else: + self.app_directory = self.servlet_context.getRealPath('/') + self.params['app_directory'] = self.app_directory + if not self.app_directory in sys.path: + sys.path.append(self.app_directory) + + def map_uri(self, req, environ): + source_uri = '%s%s%s' % (self.app_directory, File.separator, self.params['app_filename']) + callable_name = self.params['app_callable_name'] + if self.params['callable_query_name']: + query_string = req.getQueryString() + if query_string and '=' in query_string: + for name_val in query_string.split('&'): + name, value = name_val.split('=') + if name == self.params['callable_query_name']: + callable_name = value + return source_uri, callable_name + + def get_app_object(self, req, environ): + environ["SCRIPT_NAME"] = "%s%s" % (req.getContextPath(), req.getServletPath()) + path_info = req.getPathInfo() or "" + environ["PATH_INFO"] = path_info + environ["PATH_TRANSLATED"] = File(self.app_directory, path_info).getPath() + + if self.params['app_import_name'] is not None: + return self.get_app_object_importable(self.params['app_import_name']) + else: + if self.cache is None: + self.cache = {} + return self.get_app_object_old_style(req, environ) + + get_app_object = synchronize.make_synchronized(get_app_object) + + def get_app_object_importable(self, importable_name): + self.log.debug("Attempting to import application callable '%s'\n" % (importable_name, )) + # Under the importable mechanism, the cache contains a single object + if self.cache is None: + application, instantiable, method_name = self.load_importable(importable_name.strip()) + if instantiable and self.params['cache_callables']: + application = application() + self.cache = application, instantiable, method_name + application, instantiable, method_name = self.cache + self.log.debug("Application is " + str(application)) + if instantiable and not self.params['cache_callables']: + application = application() + self.log.debug("Instantiated application is " + str(application)) + if method_name is not None: + if not hasattr(application, method_name): + self.log.fatal("Attribute error application callable '%s' as no method '%s'" % (application, method_name)) + self.raise_exc(ApplicationNotFound, "Attribute error application callable '%s' as no method '%s'" % (application, method_name)) + application = getattr(application, method_name) + self.log.debug("Application method is " + str(application)) + return application + + def load_importable(self, name): + try: + instantiable = False ; method_name = None + importable_name = name + if name.find('()') != -1: + instantiable = True + importable_name, method_name = name.split('()') + if method_name.startswith('.'): + method_name = method_name[1:] + if not method_name: + method_name = None + module_path, from_name = importable_name.rsplit('.', 1) + imported = __import__(module_path, globals(), locals(), [from_name]) + imported = getattr(imported, from_name) + return imported, instantiable, method_name + except (ImportError, AttributeError), aix: + self.log.fatal("Import error import application callable '%s': %s\n" % (name, str(aix))) + self.raise_exc(ApplicationNotFound, "Failed to import app callable '%s': %s" % (name, str(aix))) + + def get_app_object_old_style(self, req, environ): + source_uri, callable_name = self.map_uri(req, environ) + source_filename = source_uri + if not self.params['cache_callables']: + self.log.debug("Caching of callables disabled") + return self.load_object(source_filename, callable_name) + if not self.cache.has_key( (source_filename, callable_name) ): + self.log.debug("Callable object not in cache: %s#%s" % (source_filename, callable_name) ) + return self.load_object(source_filename, callable_name) + app_callable, last_mod = self.cache.get( (source_filename, callable_name) ) + self.log.debug("Callable object was in cache: %s#%s" % (source_filename, callable_name) ) + if self.params['reload_on_mod']: + f = File(source_filename) + if f.lastModified() > last_mod: + self.log.info("Source file '%s' has been modified: reloading" % source_filename) + return self.load_object(source_filename, callable_name) + return app_callable + + def load_object(self, path, callable_name): + try: + app_ns = {} ; execfile(path, app_ns) + app_callable = app_ns[callable_name] + f = File(path) + self.cache[ (path, callable_name) ] = (app_callable, f.lastModified()) + return app_callable + except IOError, ioe: + self.raise_exc(ApplicationNotFound, "Application filename not found: %s" % path) + except KeyError, k: + self.raise_exc(NoCallable, "No callable named '%s' in %s" % (callable_name, path)) + except Exception, x: + self.raise_exc(NoCallable, "Error loading jython callable '%s': %s" % (callable_name, str(x)) ) + Modified: trunk/jython/Lib/modjy/modjy_response.py =================================================================== --- trunk/jython/Lib/modjy/modjy_response.py 2009-10-06 12:38:52 UTC (rev 6841) +++ trunk/jython/Lib/modjy/modjy_response.py 2009-10-06 13:11:06 UTC (rev 6842) @@ -1,113 +1,113 @@ -### -# -# Copyright Alan Kennedy. -# -# You may contact the copyright holder at this uri: -# -# http://www.xhaus.com/contact/modjy -# -# The licence under which this code is released is the Apache License v2.0. -# -# The terms and conditions of this license are listed in a file contained -# in the distribution that also contained this file, under the name -# LICENSE.txt. -# -# You may also read a copy of the license at the following web address. -# -# http://modjy.xhaus.com/LICENSE.txt -# -### - -import types - -from java.lang import System - -from modjy_exceptions import * -from modjy_write import write_object - -# From: http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1 - -hop_by_hop_headers = { - 'connection': None, - 'keep-alive': None, - 'proxy-authenticate': None, - 'proxy-authorization': None, - 'te': None, - 'trailers': None, - 'transfer-encoding': None, - 'upgrade': None, -} - -class start_response_object: - - def __init__(self, req, resp): - self.http_req = req - self.http_resp = resp - self.write_callable = None - self.called = 0 - self.content_length = None - - # I'm doing the parameters this way to facilitate porting back to java - def __call__(self, *args, **keywords): - if len(args) < 2 or len(args) > 3: - raise BadArgument("Start response callback requires either two or three arguments: got %s" % str(args)) - if len(args) == 3: - exc_info = args[2] - try: - try: - self.http_resp.reset() - except IllegalStateException, isx: - raise exc_info[0], exc_info[1], exc_info[2] - finally: - exc_info = None - else: - if self.called > 0: - raise StartResponseCalledTwice("Start response callback may only be called once, without exception information.") - status_str = args[0] - headers_list = args[1] - if not isinstance(status_str, types.StringType): - raise BadArgument("Start response callback requires string as first argument") - if not isinstance(headers_list, types.ListType): - raise BadArgument("Start response callback requires list as second argument") - try: - status_code, status_message_str = status_str.split(" ", 1) - self.http_resp.setStatus(int(status_code)) - except ValueError: - raise BadArgument("Status string must be of the form '<int> <string>'") - self.make_write_object() - try: - for header_name, header_value in headers_list: - header_name_lower = header_name.lower() - if hop_by_hop_headers.has_key(header_name_lower): - raise HopByHopHeaderSet("Under WSGI, it is illegal to set hop-by-hop headers, i.e. '%s'" % header_name) - if header_name_lower == "content-length": - try: - self.set_content_length(int(header_value)) - except ValueError, v: - raise BadArgument("Content-Length header value must be a string containing an integer, not '%s'" % header_value) - else: - final_value = header_value.encode('latin-1') - # Here would be the place to check for control characters, whitespace, etc - self.http_resp.addHeader(header_name, final_value) - except (AttributeError, TypeError), t: - raise BadArgument("Start response callback headers must contain a list of (<string>,<string>) tuples") - except UnicodeError, u: - raise BadArgument("Encoding error: header values may only contain latin-1 characters, not '%s'" % repr(header_value)) - except ValueError, v: - raise BadArgument("Headers list must contain 2-tuples") - self.called += 1 - return self.write_callable - - def set_content_length(self, length): - if self.write_callable.num_writes == 0: - self.content_length = length - self.http_resp.setContentLength(length) - else: - raise ResponseCommitted("Cannot set content-length: response is already commited.") - - def make_write_object(self): - try: - self.write_callable = write_object(self.http_resp.getOutputStream()) - except IOException, iox: - raise IOError(iox) - return self.write_callable +### +# +# Copyright Alan Kennedy. +# +# You may contact the copyright holder at this uri: +# +# http://www.xhaus.com/contact/modjy +# +# The licence under which this code is released is the Apache License v2.0. +# +# The terms and conditions of this license are listed in a file contained +# in the distribution that also contained this file, under the name +# LICENSE.txt. +# +# You may also read a copy of the license at the following web address. +# +# http://modjy.xhaus.com/LICENSE.txt +# +### + +import types + +from java.lang import System + +from modjy_exceptions import * +from modjy_write import write_object + +# From: http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1 + +hop_by_hop_headers = { + 'connection': None, + 'keep-alive': None, + 'proxy-authenticate': None, + 'proxy-authorization': None, + 'te': None, + 'trailers': None, + 'transfer-encoding': None, + 'upgrade': None, +} + +class start_response_object: + + def __init__(self, req, resp): + self.http_req = req + self.http_resp = resp + self.write_callable = None + self.called = 0 + self.content_length = None + + # I'm doing the parameters this way to facilitate porting back to java + def __call__(self, *args, **keywords): + if len(args) < 2 or len(args) > 3: + raise BadArgument("Start response callback requires either two or three arguments: got %s" % str(args)) + if len(args) == 3: + exc_info = args[2] + try: + try: + self.http_resp.reset() + except IllegalStateException, isx: + raise exc_info[0], exc_info[1], exc_info[2] + finally: + exc_info = None + else: + if self.called > 0: + raise StartResponseCalledTwice("Start response callback may only be called once, without exception information.") + status_str = args[0] + headers_list = args[1] + if not isinstance(status_str, types.StringType): + raise BadArgument("Start response callback requires string as first argument") + if not isinstance(headers_list, types.ListType): + raise BadArgument("Start response callback requires list as second argument") + try: + status_code, status_message_str = status_str.split(" ", 1) + self.http_resp.setStatus(int(status_code)) + except ValueError: + raise BadArgument("Status string must be of the form '<int> <string>'") + self.make_write_object() + try: + for header_name, header_value in headers_list: + header_name_lower = header_name.lower() + if hop_by_hop_headers.has_key(header_name_lower): + raise HopByHopHeaderSet("Under WSGI, it is illegal to set hop-by-hop headers, i.e. '%s'" % header_name) + if header_name_lower == "content-length": + try: + self.set_content_length(int(header_value)) + except ValueError, v: + raise BadArgument("Content-Length header value must be a string containing an integer, not '%s'" % header_value) + else: + final_value = header_value.encode('latin-1') + # Here would be the place to check for control characters, whitespace, etc + self.http_resp.addHeader(header_name, final_value) + except (AttributeError, TypeError), t: + raise BadArgument("Start response callback headers must contain a list of (<string>,<string>) tuples") + except UnicodeError, u: + raise BadArgument("Encoding error: header values may only contain latin-1 characters, not '%s'" % repr(header_value)) + except ValueError, v: + raise BadArgument("Headers list must contain 2-tuples") + self.called += 1 + return self.write_callable + + def set_content_length(self, length): + if self.write_callable.num_writes == 0: + self.content_length = length + self.http_resp.setContentLength(length) + else: + raise ResponseCommitted("Cannot set content-length: response is already commited.") + + def make_write_object(self): + try: + self.write_callable = write_object(self.http_resp.getOutputStream()) + except IOException, iox: + raise IOError(iox) + return self.write_callable Modified: trunk/jython/Lib/modjy/modjy_write.py =================================================================== --- trunk/jython/Lib/modjy/modjy_write.py 2009-10-06 12:38:52 UTC (rev 6841) +++ trunk/jython/Lib/modjy/modjy_write.py 2009-10-06 13:11:06 UTC (rev 6842) @@ -1,43 +1,43 @@ -### -# -# Copyright Alan Kennedy. -# -# You may contact the copyright holder at this uri: -# -# http://www.xhaus.com/contact/modjy -# -# The licence under which this code is released is the Apache License v2.0. -# -# The terms and conditions of this license are listed in a file contained -# in the distribution that also contained this file, under the name -# LICENSE.txt. -# -# You may also read a copy of the license at the following web address. -# -# http://modjy.xhaus.com/LICENSE.txt -# -### - -import types - -from modjy_exceptions import * - -class write_object: - - def __init__(self, ostream): - self.ostream = ostream - self.num_writes = 0 - - def __call__(self, *args, **keywords): - if len(args) != 1 or not isinstance(args[0], types.StringTypes): - raise NonStringOutput("Invocation of write callable requires exactly one string argument") - try: - self.ostream.write(args[0]) # Jython implicitly converts the (binary) string to a byte array - # WSGI requires that all output be flushed before returning to the application - # According to the java docs: " The flush method of OutputStream does nothing." - # Still, leave it in place for now: it's in the right place should this - # code ever be ported to another platform. - self.ostream.flush() - self.num_writes += 1 - except Exception, x: - raise ModjyIOException(x) +### +# +# Copyright Alan Kennedy. +# +# You may contact the copyright holder at this uri: +# +# http://www.xhaus.com/contact/modjy +# +# The licence under which this code is released is the Apache License v2.0. +# +# The terms and conditions of this license are listed in a file contained +# in the distribution that also contained this file, under the name +# LICENSE.txt. +# +# You may also read a copy of the license at the following web address. +# +# http://modjy.xhaus.com/LICENSE.txt +# +### + +import types + +from modjy_exceptions import * + +class write_object: + + def __init__(self, ostream): + self.ostream = ostream + self.num_writes = 0 + + def __call__(self, *args, **keywords): + if len(args) != 1 or not isinstance(args[0], types.StringTypes): + raise NonStringOutput("Invocation of write callable requires exactly one string argument") + try: + self.ostream.write(args[0]) # Jython implicitly converts the (binary) string to a byte array + # WSGI requires that all output be flushed before returning to the application + # According to the java docs: " The flush method of OutputStream does nothing." + # Still, leave it in place for now: it's in the right place should this + # code ever be ported to another platform. + self.ostream.flush() + self.num_writes += 1 + except Exception, x: + raise ModjyIOException(x) Modified: trunk/jython/Lib/modjy/modjy_wsgi.py =================================================================== --- trunk/jython/Lib/modjy/modjy_wsgi.py 2009-10-06 12:38:52 UTC (rev 6841) +++ trunk/jython/Lib/modjy/modjy_wsgi.py 2009-10-06 13:11:06 UTC (rev 6842) @@ -1,156 +1,156 @@ -### -# -# Copyright Alan Kennedy. -# -# You may contact the copyright holder at this uri: -# -# http://www.xhaus.com/contact/modjy -# -# The licence under which this code is released is the Apache License v2.0. -# -# The terms and conditions of this license are listed in a file contained -# in the distribution that also contained this file, under the name -# LICENSE.txt. -# -# You may also read a copy of the license at the following web address. -# -# http://modjy.xhaus.com/LICENS... [truncated message content] |
From: <am...@us...> - 2009-10-06 12:39:05
|
Revision: 6841 http://jython.svn.sourceforge.net/jython/?rev=6841&view=rev Author: amak Date: 2009-10-06 12:38:52 +0000 (Tue, 06 Oct 2009) Log Message: ----------- Tabs to spaces. Modified Paths: -------------- trunk/jython/tests/modjy/test_apps_dir/content_header_tests.py trunk/jython/tests/modjy/test_apps_dir/environ_tests.py trunk/jython/tests/modjy/test_apps_dir/header_tests.py trunk/jython/tests/modjy/test_apps_dir/return_tests.py trunk/jython/tests/modjy/test_apps_dir/simple_app.py trunk/jython/tests/modjy/test_apps_dir/stream_tests.py trunk/jython/tests/modjy/test_apps_dir/web_inf_tests.py Modified: trunk/jython/tests/modjy/test_apps_dir/content_header_tests.py =================================================================== --- trunk/jython/tests/modjy/test_apps_dir/content_header_tests.py 2009-10-06 12:27:51 UTC (rev 6840) +++ trunk/jython/tests/modjy/test_apps_dir/content_header_tests.py 2009-10-06 12:38:52 UTC (rev 6841) @@ -21,7 +21,7 @@ ### """ - A variety of app callables used to test content related headers. + A variety of app callables used to test content related headers. """ def test_set_content_length(environ, start_response): Modified: trunk/jython/tests/modjy/test_apps_dir/environ_tests.py =================================================================== --- trunk/jython/tests/modjy/test_apps_dir/environ_tests.py 2009-10-06 12:27:51 UTC (rev 6840) +++ trunk/jython/tests/modjy/test_apps_dir/environ_tests.py 2009-10-06 12:38:52 UTC (rev 6841) @@ -22,50 +22,50 @@ """ - A variety of app callables used to test the WSGI environment. + A variety of app callables used to test the WSGI environment. """ def test_echo_wsgi_env(environ, start_response): - writer = start_response("200 OK", []) - output_dict = {} - for k in environ["QUERY_STRING"].split(';'): - output_dict[k] = environ[k] - return [repr(output_dict)] + writer = start_response("200 OK", []) + output_dict = {} + for k in environ["QUERY_STRING"].split(';'): + output_dict[k] = environ[k] + return [repr(output_dict)] def test_env_is_dict(environ, start_response): - writer = start_response("200 OK", []) - if type(environ) is type({}): - writer("true") - else: - writer("false") - return [] + writer = start_response("200 OK", []) + if type(environ) is type({}): + writer("true") + else: + writer("false") + return [] def test_env_is_mutable(environ, start_response): - writer = start_response("200 OK", []) - try: - environ['some_key'] = 'some value' - writer("true") - except: - writer("false") - return [] + writer = start_response("200 OK", []) + try: + environ['some_key'] = 'some value' + writer("true") + except: + writer("false") + return [] def test_env_contains_request_method(environ, start_response): - writer = start_response("200 OK", []) - try: - writer(environ['REQUEST_METHOD']) - except KeyError, k: - writer(str(k)) - return [] + writer = start_response("200 OK", []) + try: + writer(environ['REQUEST_METHOD']) + except KeyError, k: + writer(str(k)) + return [] def test_env_script_name_path_info(environ, start_response): - writer = start_response("200 OK", []) - writer("%s:::%s" % (environ['SCRIPT_NAME'], environ['PATH_INFO'])) - return [] + writer = start_response("200 OK", []) + writer("%s:::%s" % (environ['SCRIPT_NAME'], environ['PATH_INFO'])) + return [] def test_env_query_string(environ, start_response): - writer = start_response("200 OK", []) - writer(environ['QUERY_STRING']) - return [] + writer = start_response("200 OK", []) + writer(environ['QUERY_STRING']) + return [] required_cgi_vars = [ 'REQUEST_METHOD', Modified: trunk/jython/tests/modjy/test_apps_dir/header_tests.py =================================================================== --- trunk/jython/tests/modjy/test_apps_dir/header_tests.py 2009-10-06 12:27:51 UTC (rev 6840) +++ trunk/jython/tests/modjy/test_apps_dir/header_tests.py 2009-10-06 12:38:52 UTC (rev 6841) @@ -21,118 +21,118 @@ ### """ - A variety of app callables used to test the WSGI headers. + A variety of app callables used to test the WSGI headers. """ def test_invalid_status_code(environ, start_response): - writer = start_response("twohundred ok", []) - # Should never get here - writer("D'oh!") - return [] + writer = start_response("twohundred ok", []) + # Should never get here + writer("D'oh!") + return [] def test_non_latin1_status_string(environ, start_response): - writer = start_response(u"200 \u03c9\u03ba", []) # "200 Omega Kappa" - # Should never get here - writer("D'oh!") - return [] + writer = start_response(u"200 \u03c9\u03ba", []) # "200 Omega Kappa" + # Should never get here + writer("D'oh!") + return [] def test_control_chars_in_status_string(environ, start_response): - writer = start_response(u"200 OK\x08\x08Hoopy", []) # "200 OK^H^HHoopy" - # Should never get here - writer("D'oh!") - return [] + writer = start_response(u"200 OK\x08\x08Hoopy", []) # "200 OK^H^HHoopy" + # Should never get here + writer("D'oh!") + return [] def test_headers_not_list(environ, start_response): - qstring = environ['QUERY_STRING'] - if qstring == '1': - headers = {} - elif qstring == '2': - headers = () - elif qstring == '3': - headers = 1 - else: - headers = None - writer = start_response("200 OK", headers) - # Should never get here - writer("D'oh!") - return [] + qstring = environ['QUERY_STRING'] + if qstring == '1': + headers = {} + elif qstring == '2': + headers = () + elif qstring == '3': + headers = 1 + else: + headers = None + writer = start_response("200 OK", headers) + # Should never get here + writer("D'oh!") + return [] def test_headers_list_non_tuples(environ, start_response): - qstring = environ['QUERY_STRING'] - if qstring == '1': - header = {} - elif qstring == '2': - header = [] - elif qstring == '3': - header = 1 - else: - header = None - headers = [header] - writer = start_response("200 OK", headers) - # Should never get here - writer("D'oh!") - return [] + qstring = environ['QUERY_STRING'] + if qstring == '1': + header = {} + elif qstring == '2': + header = [] + elif qstring == '3': + header = 1 + else: + header = None + headers = [header] + writer = start_response("200 OK", headers) + # Should never get here + writer("D'oh!") + return [] def test_headers_list_wrong_length_tuples(environ, start_response): - qstring = environ['QUERY_STRING'] - length = int(qstring) - if length == 2: length = 3 - header_tuple = tuple(range(int(qstring))) - headers = [header_tuple] - writer = start_response("200 OK", headers) - # Should never get here - writer("D'oh!") - return [] + qstring = environ['QUERY_STRING'] + length = int(qstring) + if length == 2: length = 3 + header_tuple = tuple(range(int(qstring))) + headers = [header_tuple] + writer = start_response("200 OK", headers) + # Should never get here + writer("D'oh!") + return [] def test_headers_list_wrong_types_in_tuples(environ, start_response): - qstring = environ['QUERY_STRING'] - if qstring == '1': - headers = [(1, 1)] - elif qstring == '2': - headers = [('header_name', 1L)] - elif qstring == '3': - headers = [('header_name', None)] - elif qstring == '4': - headers = [('header_name', 42.0)] - else: - headers = [(None, 'value')] - writer = start_response("200 OK", headers) - # Should never get here - writer("D'oh!") - return [] + qstring = environ['QUERY_STRING'] + if qstring == '1': + headers = [(1, 1)] + elif qstring == '2': + headers = [('header_name', 1L)] + elif qstring == '3': + headers = [('header_name', None)] + elif qstring == '4': + headers = [('header_name', 42.0)] + else: + headers = [(None, 'value')] + writer = start_response("200 OK", headers) + # Should never get here + writer("D'oh!") + return [] def test_headers_list_contains_non_latin1_values(environ, start_response): - headers = [('x-unicoded-header', u'\u03b1\u03b2\u03b3\u03b4\u03b5')] - writer = start_response("200 OK", headers) - # Should never get here - writer("D'oh!") - return [] + headers = [('x-unicoded-header', u'\u03b1\u03b2\u03b3\u03b4\u03b5')] + writer = start_response("200 OK", headers) + # Should never get here + writer("D'oh!") + return [] def test_headers_list_contains_values_with_control_chars(environ, start_response): - headers = [('x-control-coded-header', 'your father smelled of elder\x08\x08\x08\x08\x08loganberries')] - writer = start_response("200 OK", headers) - # Should never get here - writer("D'oh!") - return [] + headers = [('x-control-coded-header', 'your father smelled of elder\x08\x08\x08\x08\x08loganberries')] + writer = start_response("200 OK", headers) + # Should never get here + writer("D'oh!") + return [] def test_headers_list_contains_accented_latin1_values(environ, start_response): - name, value = environ['QUERY_STRING'].split('=') - headers = [(name, value)] - writer = start_response("200 OK", headers) - writer("Doesn't matter") - return [] + name, value = environ['QUERY_STRING'].split('=') + headers = [(name, value)] + writer = start_response("200 OK", headers) + writer("Doesn't matter") + return [] def test_headers_list_contains_accented_latin1_values(environ, start_response): - name, value = environ['QUERY_STRING'].split('=') - headers = [(name, value)] - writer = start_response("200 OK", headers) - writer("Doesn't matter") - return [] + name, value = environ['QUERY_STRING'].split('=') + headers = [(name, value)] + writer = start_response("200 OK", headers) + writer("Doesn't matter") + return [] def test_hop_by_hop(environ, start_response): - qstring = environ['QUERY_STRING'] - headers = [(qstring, 'doesnt matter')] - writer = start_response("200 OK", headers) - # Should never get here - writer("D'oh!") - return [] + qstring = environ['QUERY_STRING'] + headers = [(qstring, 'doesnt matter')] + writer = start_response("200 OK", headers) + # Should never get here + writer("D'oh!") + return [] Modified: trunk/jython/tests/modjy/test_apps_dir/return_tests.py =================================================================== --- trunk/jython/tests/modjy/test_apps_dir/return_tests.py 2009-10-06 12:27:51 UTC (rev 6840) +++ trunk/jython/tests/modjy/test_apps_dir/return_tests.py 2009-10-06 12:38:52 UTC (rev 6841) @@ -21,18 +21,18 @@ ### """ - A variety of app callables used to test return types. + A variety of app callables used to test return types. """ def test_non_iterable_return(environ, start_response): writer = start_response("200 OK", []) query_string = environ['QUERY_STRING'] return_object = { - 'int': 42, - 'float': 42.0, - 'str': "Strings are not permitted return values", - 'unicode': u"Unicode strings are not permitted return values", - 'none': None, + 'int': 42, + 'float': 42.0, + 'str': "Strings are not permitted return values", + 'unicode': u"Unicode strings are not permitted return values", + 'none': None, }[query_string] return return_object @@ -40,9 +40,9 @@ writer = start_response("200 OK", []) query_string = environ['QUERY_STRING'] return_object = { - 'int': 42, - 'float': 42.0, - 'none': None, + 'int': 42, + 'float': 42.0, + 'none': None, }[query_string] return [return_object] Modified: trunk/jython/tests/modjy/test_apps_dir/simple_app.py =================================================================== --- trunk/jython/tests/modjy/test_apps_dir/simple_app.py 2009-10-06 12:27:51 UTC (rev 6840) +++ trunk/jython/tests/modjy/test_apps_dir/simple_app.py 2009-10-06 12:38:52 UTC (rev 6841) @@ -22,6 +22,6 @@ def simple_app(environ, start_response): - writer = start_response("200 OK", []) - writer("Hello World!") - return [] + writer = start_response("200 OK", []) + writer("Hello World!") + return [] Modified: trunk/jython/tests/modjy/test_apps_dir/stream_tests.py =================================================================== --- trunk/jython/tests/modjy/test_apps_dir/stream_tests.py 2009-10-06 12:27:51 UTC (rev 6840) +++ trunk/jython/tests/modjy/test_apps_dir/stream_tests.py 2009-10-06 12:38:52 UTC (rev 6841) @@ -21,80 +21,78 @@ ### """ - A variety of app callables used to test the WSGI streams. + A variety of app callables used to test the WSGI streams. """ from UserDict import UserDict def extract_params(qstring): - params = {} - if qstring: - name_vals = [t.split('=', 1) for t in qstring.split('&')] - for n, v in name_vals: params[n] = v - return params + params = {} + if qstring: + name_vals = [t.split('=', 1) for t in qstring.split('&')] + for n, v in name_vals: params[n] = v + return params def test_read_input_stream(environ, start_response): - writer = start_response("200 OK", []) - wsgi_input = environ['wsgi.input'] - params = extract_params(environ['QUERY_STRING']) - readsize = None - if params.has_key('readsize'): - readsize = int(params['readsize']) - if readsize: - pieces = [] - piece = wsgi_input.read(readsize) - while piece: - pieces.append(piece) - piece = wsgi_input.read(readsize) - data = ''.join(pieces) - else: - data = wsgi_input.read() - output_dict = {'data': data} - writer(repr(output_dict)) - return [] + writer = start_response("200 OK", []) + wsgi_input = environ['wsgi.input'] + params = extract_params(environ['QUERY_STRING']) + readsize = None + if params.has_key('readsize'): + readsize = int(params['readsize']) + if readsize: + pieces = [] + piece = wsgi_input.read(readsize) + while piece: + pieces.append(piece) + piece = wsgi_input.read(readsize) + data = ''.join(pieces) + else: + data = wsgi_input.read() + output_dict = {'data': data} + writer(repr(output_dict)) + return [] def test_readline_input_stream(environ, start_response): - writer = start_response("200 OK", []) - wsgi_input = environ['wsgi.input'] - params = extract_params(environ['QUERY_STRING']) - readsize = None - if params.has_key('readsize'): - readsize = int(params['readsize']) - if readsize: - data = wsgi_input.readline(readsize) - else: - data = wsgi_input.readline() - output_dict = {'data': data} - writer(repr(output_dict)) - return [] + writer = start_response("200 OK", []) + wsgi_input = environ['wsgi.input'] + params = extract_params(environ['QUERY_STRING']) + readsize = None + if params.has_key('readsize'): + readsize = int(params['readsize']) + if readsize: + data = wsgi_input.readline(readsize) + else: + data = wsgi_input.readline() + output_dict = {'data': data} + writer(repr(output_dict)) + return [] def test_readlines_input_stream(environ, start_response): - writer = start_response("200 OK", []) - wsgi_input = environ['wsgi.input'] - params = extract_params(environ['QUERY_STRING']) - readsize = None - if params.has_key('readsize'): - readsize = int(params['readsize']) - if readsize: - data = wsgi_input.readlines(readsize) - else: - data = wsgi_input.readlines() - output_dict = {'data': "$".join(data)} - writer(repr(output_dict)) - return [] + writer = start_response("200 OK", []) + wsgi_input = environ['wsgi.input'] + params = extract_params(environ['QUERY_STRING']) + readsize = None + if params.has_key('readsize'): + readsize = int(params['readsize']) + if readsize: + data = wsgi_input.readlines(readsize) + else: + data = wsgi_input.readlines() + output_dict = {'data': "$".join(data)} + writer(repr(output_dict)) + return [] def test_error_stream(environ, start_response): - writer = start_response("200 OK", []) - wsgi_errors = environ['wsgi.errors'] - error_msg = None - for method in ['flush', 'write', 'writelines', ]: - if not hasattr(wsgi_errors, method): - error_msg = "wsgi.errors has no '%s' attr" % method - if not error_msg and not callable(getattr(wsgi_errors, method)): - error_msg = "wsgi.errors.%s attr is not callable" % method - if error_msg: break - return_msg = error_msg or "success" - writer(return_msg) - return [] - - \ No newline at end of file + writer = start_response("200 OK", []) + wsgi_errors = environ['wsgi.errors'] + error_msg = None + for method in ['flush', 'write', 'writelines', ]: + if not hasattr(wsgi_errors, method): + error_msg = "wsgi.errors has no '%s' attr" % method + if not error_msg and not callable(getattr(wsgi_errors, method)): + error_msg = "wsgi.errors.%s attr is not callable" % method + if error_msg: break + return_msg = error_msg or "success" + writer(return_msg) + return [] Modified: trunk/jython/tests/modjy/test_apps_dir/web_inf_tests.py =================================================================== --- trunk/jython/tests/modjy/test_apps_dir/web_inf_tests.py 2009-10-06 12:27:51 UTC (rev 6840) +++ trunk/jython/tests/modjy/test_apps_dir/web_inf_tests.py 2009-10-06 12:38:52 UTC (rev 6841) @@ -22,7 +22,7 @@ """ - A variety of app callables used to test WEB-INF interactions. + A variety of app callables used to test WEB-INF interactions. """ def test_import_from_lib_python(environ, start_response): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <am...@us...> - 2009-10-06 12:27:59
|
Revision: 6840 http://jython.svn.sourceforge.net/jython/?rev=6840&view=rev Author: amak Date: 2009-10-06 12:27:51 +0000 (Tue, 06 Oct 2009) Log Message: ----------- Adding proper interpreter shutdown on servlet.destroy() for modjy. Fixes: http://bugs.jython.org/issue1474 Thanks to Colin Evans for reporting the issue. Modified Paths: -------------- trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java Added Paths: ----------- trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestServletLifecycle.java trunk/jython/tests/modjy/test_apps_dir/lifecycle_tests.py Modified: trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java =================================================================== --- trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java 2009-10-04 23:25:51 UTC (rev 6839) +++ trunk/jython/src/com/xhaus/modjy/ModjyJServlet.java 2009-10-06 12:27:51 UTC (rev 6840) @@ -127,6 +127,15 @@ } /** + * Close down the modjy servlet. + * + */ + @Override + public void destroy( ) { + interp.cleanup(); + } + + /** * Setup the modjy environment, i.e. 1. Find the location of the modjy.jar file and add it to * sys.path 2. Process the WEB-INF/lib-python directory, if it exists * Modified: trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java =================================================================== --- trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java 2009-10-04 23:25:51 UTC (rev 6839) +++ trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestBase.java 2009-10-06 12:27:51 UTC (rev 6840) @@ -194,7 +194,7 @@ super.setUp(); String jythonHome = System.getProperty("JYTHON_HOME"); setRealPath(jythonHome, jythonHome); - setRealPath("/WEB-INF/" + LIB_PYTHON_DIR, LIB_PYTHON_TEST_PATH); + setRealPath("/WEB-INF/" + LIB_PYTHON_DIR, LIB_PYTHON_TEST_PATH); setRealPath("/WEB-INF/lib/modjy.jar", "../modjy.jar"); setPythonHome(jythonHome); setAppDir(DEFAULT_APP_DIR); @@ -238,6 +238,7 @@ suite.addTestSuite(ModjyTestHeaders.class); suite.addTestSuite(ModjyTestContentHeaders.class); suite.addTestSuite(ModjyTestReturnIterable.class); + suite.addTestSuite(ModjyTestServletLifecycle.class); suite.addTestSuite(ModjyTestWebInf.class); suite.addTestSuite(ModjyTestWSGIStreams.class); suite.addTestSuite(PyServletTest.class); Added: trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestServletLifecycle.java =================================================================== --- trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestServletLifecycle.java (rev 0) +++ trunk/jython/tests/modjy/java/com/xhaus/modjy/ModjyTestServletLifecycle.java 2009-10-06 12:27:51 UTC (rev 6840) @@ -0,0 +1,42 @@ +/*### +# +# Copyright Alan Kennedy. +# +# You may contact the copyright holder at this uri: +# +# http://www.xhaus.com/contact/modjy +# +# The licence under which this code is released is the Apache License v2.0. +# +# The terms and conditions of this license are listed in a file contained +# in the distribution that also contained this file, under the name +# LICENSE.txt. +# +# You may also read a copy of the license at the following web address. +# +# http://modjy.xhaus.com/LICENSE.txt +# +###*/ + +package com.xhaus.modjy; + +import javax.servlet.http.HttpServlet; + +public class ModjyTestServletLifecycle extends ModjyTestBase { + + protected void lifecycleTestSetUp() throws Exception { + baseSetUp(); + setAppFile("lifecycle_tests.py"); + } + + public void testAtExitHandlersCalled() throws Exception { + System.setProperty("modjy", "here"); + lifecycleTestSetUp(); + createServlet(); + doGet(); + HttpServlet modjyServlet = getServlet(); + modjyServlet.destroy(); + assertEquals("gone", System.getProperty("modjy")); + } + +} Added: trunk/jython/tests/modjy/test_apps_dir/lifecycle_tests.py =================================================================== --- trunk/jython/tests/modjy/test_apps_dir/lifecycle_tests.py (rev 0) +++ trunk/jython/tests/modjy/test_apps_dir/lifecycle_tests.py 2009-10-06 12:27:51 UTC (rev 6840) @@ -0,0 +1,34 @@ +# -*- coding: windows-1252 -*- + +### +# +# Copyright Alan Kennedy. +# +# You may contact the copyright holder at this uri: +# +# http://www.xhaus.com/contact/modjy +# +# The licence under which this code is released is the Apache License v2.0. +# +# The terms and conditions of this license are listed in a file contained +# in the distribution that also contained this file, under the name +# LICENSE.txt. +# +# You may also read a copy of the license at the following web address. +# +# http://modjy.xhaus.com/LICENSE.txt +# +### + +import atexit + +def exit_func(): + import java + java.lang.System.setProperty("modjy", "gone") + +atexit.register(exit_func) + +def lifecycle_test(environ, start_response): + writer = start_response("200 OK", []) + writer("Hello World!") + return [] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-04 23:26:14
|
Revision: 6839 http://jython.svn.sourceforge.net/jython/?rev=6839&view=rev Author: pjenvey Date: 2009-10-04 23:25:51 +0000 (Sun, 04 Oct 2009) Log Message: ----------- only abspath module __file__s. the only other type having __file__ here is javapackage and their jar paths are already canonicalized by packagecache. saves maybe 150ms off startup Modified Paths: -------------- trunk/jython/Lib/site.py Modified: trunk/jython/Lib/site.py =================================================================== --- trunk/jython/Lib/site.py 2009-10-04 22:31:22 UTC (rev 6838) +++ trunk/jython/Lib/site.py 2009-10-04 23:25:51 UTC (rev 6839) @@ -60,6 +60,7 @@ import sys import os +import types import __builtin__ @@ -73,8 +74,10 @@ def abs__file__(): """Set all module' __file__ attribute to an absolute path""" for m in sys.modules.values(): - if hasattr(m, '__loader__'): - continue # don't mess with a PEP 302-supplied __file__ + if not isinstance(m, types.ModuleType) or hasattr(m, '__loader__'): + # only modules need the abspath in Jython. and don't mess + # with a PEP 302-supplied __file__ + continue f = getattr(m, '__file__', None) if f is None: continue This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-04 22:31:34
|
Revision: 6838 http://jython.svn.sourceforge.net/jython/?rev=6838&view=rev Author: fwierzbicki Date: 2009-10-04 22:31:22 +0000 (Sun, 04 Oct 2009) Log Message: ----------- switch to p() from raw path strings where possible, also some cleanup. 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-04 21:25:41 UTC (rev 6837) +++ trunk/jython/src/org/python/compiler/Module.java 2009-10-04 22:31:22 UTC (rev 6838) @@ -27,6 +27,7 @@ import org.python.core.PyInteger; import org.python.core.PyLong; import org.python.core.PyObject; +import org.python.core.PyRunnable; import org.python.core.PyRunnableBootstrap; import org.python.core.PyString; import org.python.core.PyUnicode; @@ -52,7 +53,7 @@ public void put(Code c) throws IOException { module.classfile.addField(name, ci(PyInteger.class), access); c.iconst(value); - c.invokestatic("org/python/core/Py", "newInteger", sig(PyInteger.class, Integer.TYPE)); + c.invokestatic(p(Py.class), "newInteger", sig(PyInteger.class, Integer.TYPE)); c.putstatic(module.classfile.name, name, ci(PyInteger.class)); } @@ -63,10 +64,11 @@ @Override public boolean equals(Object o) { - if (o instanceof PyIntegerConstant) + if (o instanceof PyIntegerConstant) { return ((PyIntegerConstant)o).value == value; - else + } else { return false; + } } } @@ -85,7 +87,7 @@ public void put(Code c) throws IOException { module.classfile.addField(name, ci(PyFloat.class), access); c.ldc(new Double(value)); - c.invokestatic("org/python/core/Py", "newFloat", sig(PyFloat.class, Double.TYPE)); + c.invokestatic(p(Py.class), "newFloat", sig(PyFloat.class, Double.TYPE)); c.putstatic(module.classfile.name, name, ci(PyFloat.class)); } @@ -96,10 +98,11 @@ @Override public boolean equals(Object o) { - if (o instanceof PyFloatConstant) + if (o instanceof PyFloatConstant) { return ((PyFloatConstant)o).value == value; - else + } else { return false; + } } } @@ -118,7 +121,7 @@ public void put(Code c) throws IOException { module.classfile.addField(name, ci(PyComplex.class), access); c.ldc(new Double(value)); - c.invokestatic("org/python/core/Py", "newImaginary", sig(PyComplex.class, Double.TYPE)); + c.invokestatic(p(Py.class), "newImaginary", sig(PyComplex.class, Double.TYPE)); c.putstatic(module.classfile.name, name, ci(PyComplex.class)); } @@ -129,10 +132,11 @@ @Override public boolean equals(Object o) { - if (o instanceof PyComplexConstant) + if (o instanceof PyComplexConstant) { return ((PyComplexConstant)o).value == value; - else + } else { return false; + } } } @@ -151,8 +155,7 @@ public void put(Code c) throws IOException { module.classfile.addField(name, ci(PyString.class), access); c.ldc(value); - c.invokestatic("org/python/core/PyString", "fromInterned", sig(PyString.class, - String.class)); + c.invokestatic(p(PyString.class), "fromInterned", sig(PyString.class, String.class)); c.putstatic(module.classfile.name, name, ci(PyString.class)); } @@ -163,10 +166,11 @@ @Override public boolean equals(Object o) { - if (o instanceof PyStringConstant) + if (o instanceof PyStringConstant) { return ((PyStringConstant)o).value.equals(value); - else + } else { return false; + } } } @@ -185,8 +189,7 @@ public void put(Code c) throws IOException { module.classfile.addField(name, ci(PyUnicode.class), access); c.ldc(value); - c.invokestatic("org/python/core/PyUnicode", "fromInterned", sig(PyUnicode.class, - String.class)); + c.invokestatic(p(PyUnicode.class), "fromInterned", sig(PyUnicode.class, String.class)); c.putstatic(module.classfile.name, name, ci(PyUnicode.class)); } @@ -197,10 +200,11 @@ @Override public boolean equals(Object o) { - if (o instanceof PyUnicodeConstant) + if (o instanceof PyUnicodeConstant) { return ((PyUnicodeConstant)o).value.equals(value); - else + } else { return false; + } } } @@ -219,7 +223,7 @@ public void put(Code c) throws IOException { module.classfile.addField(name, ci(PyLong.class), access); c.ldc(value); - c.invokestatic("org/python/core/Py", "newLong", sig(PyLong.class, String.class)); + c.invokestatic(p(Py.class), "newLong", sig(PyLong.class, String.class)); c.putstatic(module.classfile.name, name, ci(PyLong.class)); } @@ -230,9 +234,11 @@ @Override public boolean equals(Object o) { - if (o instanceof PyLongConstant) + if (o instanceof PyLongConstant) { return ((PyLongConstant)o).value.equals(value); - else return false; + } else { + return false; + } } } @@ -301,7 +307,7 @@ c.iconst(moreflags); - c.invokestatic("org/python/core/Py", "newCode", sig(PyCode.class, Integer.TYPE, + c.invokestatic(p(Py.class), "newCode", sig(PyCode.class, Integer.TYPE, String[].class, String.class, String.class, Integer.TYPE, Boolean.TYPE, Boolean.TYPE, PyFunctionTable.class, Integer.TYPE, String[].class, String[].class, Integer.TYPE, Integer.TYPE)); @@ -327,14 +333,15 @@ public Module(String name, String filename, boolean linenumbers, long mtime) { this.linenumbers = linenumbers; this.mtime = mtime; - classfile = new ClassFile(name, "org/python/core/PyFunctionTable", + classfile = new ClassFile(name, p(PyFunctionTable.class), ACC_SYNCHRONIZED | ACC_PUBLIC, mtime); constants = new Hashtable<Constant,Constant>(); sfilename = filename; - if (filename != null) + if (filename != null) { this.filename = PyString(filename); - else + } else { this.filename = null; + } codes = new ArrayList<PyCodeConstant>(); futures = new Future(); scopes = new Hashtable<PythonTree,ScopeInfo>(); @@ -349,8 +356,9 @@ private Constant findConstant(Constant c) { Constant ret = constants.get(c); - if (ret != null) + if (ret != null) { return ret; + } ret = c; c.module = this; //More sophisticated name mappings might be nice @@ -374,9 +382,11 @@ public Constant PyString(String value) { return findConstant(new PyStringConstant(value)); } + public Constant PyUnicode(String value) { return findConstant(new PyUnicodeConstant(value)); } + public Constant PyLong(String value) { return findConstant(new PyLongConstant(value)); } @@ -384,14 +394,17 @@ List<PyCodeConstant> codes; private boolean isJavaIdentifier(String s) { char[] chars = s.toCharArray(); - if (chars.length == 0) + if (chars.length == 0) { return false; - if (!Character.isJavaIdentifierStart(chars[0])) + } + if (!Character.isJavaIdentifierStart(chars[0])) { return false; + } for(int i=1; i<chars.length; i++) { - if (!Character.isJavaIdentifierPart(chars[i])) + if (!Character.isJavaIdentifierPart(chars[i])) { return false; + } } return true; } @@ -399,7 +412,9 @@ //XXX: this can probably go away now that we can probably just copy the list. private List<String> toNameAr(List<String> names,boolean nullok) { int sz = names.size(); - if (sz == 0 && nullok) return null; + if (sz == 0 && nullok) { + return null; + } List<String> nameArray = new ArrayList<String>(); nameArray.addAll(names); return nameArray; @@ -461,10 +476,8 @@ c.aload(1); c.ldc("__name__"); - c.invokevirtual("org/python/core/PyFrame", "getname", sig(PyObject.class, - String.class)); - - c.invokevirtual("org/python/core/PyFrame", "setlocal", sig(Void.TYPE, String.class, + c.invokevirtual(p(PyFrame.class), "getname", sig(PyObject.class, String.class)); + c.invokevirtual(p(PyFrame.class), "setlocal", sig(Void.TYPE, String.class, PyObject.class)); } @@ -488,21 +501,19 @@ SymInfo syminf = tbl.get(paramcells.get(i)); c.iconst(syminf.locals_index); c.iconst(syminf.env_index); - c.invokevirtual("org/python/core/PyFrame", "to_cell", sig(Void.TYPE, Integer.TYPE, + c.invokevirtual(p(PyFrame.class), "to_cell", sig(Void.TYPE, Integer.TYPE, Integer.TYPE)); } } - compiler.parse(tree, c, fast_locals, className, classBody, - scope, cflags); + 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("org/python/core/PyFrame", "f_lasti", "I"); + c.getfield(p(PyFrame.class), "f_lasti", "I"); Label[] yields = new Label[compiler.yields.size()+1]; yields[0] = start; @@ -543,7 +554,7 @@ public void addInit() throws IOException { Code c = classfile.addMethod("<init>", sig(Void.TYPE, String.class), ACC_PUBLIC); c.aload(0); - c.invokespecial("org/python/core/PyFunctionTable", "<init>", sig(Void.TYPE)); + c.invokespecial(p(PyFunctionTable.class), "<init>", sig(Void.TYPE)); addConstants(c); } @@ -570,8 +581,7 @@ } public void addBootstrap() throws IOException { - Code c = classfile.addMethod(CodeLoader.GET_BOOTSTRAP_METHOD_NAME, - sig(CodeBootstrap.class), + Code c = classfile.addMethod(CodeLoader.GET_BOOTSTRAP_METHOD_NAME, sig(CodeBootstrap.class), ACC_PUBLIC | ACC_STATIC); c.ldc(Type.getType("L" + classfile.name + ";")); c.invokestatic(p(PyRunnableBootstrap.class), PyRunnableBootstrap.REFLECTION_METHOD_NAME, @@ -580,8 +590,7 @@ } public void addConstants(Code c) throws IOException { - classfile.addField("self", "L"+classfile.name+";", - ACC_STATIC|ACC_FINAL); + classfile.addField("self", "L"+classfile.name+";", ACC_STATIC|ACC_FINAL); c.aload(0); c.putstatic(classfile.name, "self", "L"+classfile.name+";"); Enumeration e = constants.elements(); @@ -600,10 +609,8 @@ } public void addFunctions() throws IOException { - Code code = classfile.addMethod( - "call_function", - sig(PyObject.class, Integer.TYPE, PyFrame.class, ThreadState.class), - ACC_PUBLIC); + Code code = classfile.addMethod("call_function", + sig(PyObject.class, Integer.TYPE, PyFrame.class, ThreadState.class), ACC_PUBLIC); code.aload(0); // this code.aload(2); // frame @@ -638,7 +645,7 @@ addFunctions(); - classfile.addInterface("org/python/core/PyRunnable"); + classfile.addInterface(p(PyRunnable.class)); if (sfilename != null) { classfile.setSource(sfilename); } @@ -659,8 +666,7 @@ { if (!err) { try { - Py.warning(Py.SyntaxWarning, msg, - (sfilename != null) ? sfilename : "?", + Py.warning(Py.SyntaxWarning, msg, (sfilename != null) ? sfilename : "?", node.getLine() ,null, Py.None); return; } catch(PyException e) { @@ -676,7 +682,8 @@ CompilerFlags cflags) throws Exception { - compile(node, ostream, name, filename, linenumbers, printResults, cflags, org.python.core.imp.NO_MTIME); + compile(node, ostream, name, filename, linenumbers, printResults, cflags, + org.python.core.imp.NO_MTIME); } public static void compile(mod node, OutputStream ostream, This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-04 21:25:59
|
Revision: 6837 http://jython.svn.sourceforge.net/jython/?rev=6837&view=rev Author: pjenvey Date: 2009-10-04 21:25:41 +0000 (Sun, 04 Oct 2009) Log Message: ----------- hack around PyReflectedFunction's assumption of how instancemethod calls into it so instancemethod's ThreadState pass through optimization can be enabled Modified Paths: -------------- trunk/jython/src/org/python/core/PyMethod.java trunk/jython/src/org/python/core/PyReflectedConstructor.java trunk/jython/src/org/python/core/PyReflectedFunction.java trunk/jython/src/org/python/core/ReflectedArgs.java Modified: trunk/jython/src/org/python/core/PyMethod.java =================================================================== --- trunk/jython/src/org/python/core/PyMethod.java 2009-10-04 20:16:12 UTC (rev 6836) +++ trunk/jython/src/org/python/core/PyMethod.java 2009-10-04 21:25:41 UTC (rev 6837) @@ -94,7 +94,7 @@ return this; } } - /*// This has been disabled since JavaFunc expects to be called with self + boxed args + @Override public PyObject __call__() { return __call__(Py.getThreadState()); @@ -146,8 +146,7 @@ } @Override - public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, - PyObject arg2) { + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, PyObject arg2) { PyObject self = checkSelf(arg0, null); if (self == null) { return im_func.__call__(state, arg0, arg1, arg2); @@ -162,17 +161,17 @@ } @Override - public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, - PyObject arg2, PyObject arg3) { + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, PyObject arg2, + PyObject arg3) { PyObject self = checkSelf(arg0, null); if (self == null) { return im_func.__call__(state, arg0, arg1, arg2, arg3); } else { - return im_func.__call__(state, self, new PyObject[]{arg0, arg1, arg2, arg3}, Py.NoKeywords); + return im_func.__call__(state, self, new PyObject[]{arg0, arg1, arg2, arg3}, + Py.NoKeywords); } } - @Override public PyObject __call__(PyObject arg1, PyObject[] args, String[] keywords) { return __call__(Py.getThreadState(), arg1, args, keywords); @@ -180,15 +179,15 @@ @Override public PyObject __call__(ThreadState state, PyObject arg1, PyObject[] args, - String[] keywords) { + String[] keywords) { PyObject self = checkSelf(arg1, args); if (self == null) { return im_func.__call__(state, arg1, args, keywords); } else { - PyObject[] new_args = new PyObject[args.length+1]; - System.arraycopy(args, 0, new_args, 1, args.length); - new_args[0] = arg1; - return im_func.__call__(state, self, new_args, keywords); + PyObject[] newArgs = new PyObject[args.length + 1]; + System.arraycopy(args, 0, newArgs, 1, args.length); + newArgs[0] = arg1; + return im_func.__call__(state, self, newArgs, keywords); } } @@ -201,14 +200,19 @@ public PyObject __call__(ThreadState state, PyObject[] args) { return __call__(state, args, Py.NoKeywords); } - */ + @Override public PyObject __call__(PyObject[] args, String[] keywords) { - return instancemethod___call__(args, keywords); + return __call__(Py.getThreadState(), args, keywords); } @Override public PyObject __call__(ThreadState state, PyObject[] args, String[] keywords) { + return instancemethod___call__(state, args, keywords); + } + + @ExposedMethod(doc = BuiltinDocs.instancemethod___call___doc) + final PyObject instancemethod___call__(ThreadState state, PyObject[] args, String[] keywords) { PyObject self = checkSelf(null, args); if (self == null) { return im_func.__call__(state, args, keywords); @@ -216,11 +220,6 @@ return im_func.__call__(state, self, args, keywords); } } - - @ExposedMethod(doc = BuiltinDocs.instancemethod___call___doc) - final PyObject instancemethod___call__(PyObject[] args, String[] keywords) { - return __call__(Py.getThreadState(), args, keywords); - } private PyObject checkSelf(PyObject arg, PyObject[] args) { PyObject self = im_self; Modified: trunk/jython/src/org/python/core/PyReflectedConstructor.java =================================================================== --- trunk/jython/src/org/python/core/PyReflectedConstructor.java 2009-10-04 20:16:12 UTC (rev 6836) +++ trunk/jython/src/org/python/core/PyReflectedConstructor.java 2009-10-04 21:25:41 UTC (rev 6837) @@ -77,6 +77,7 @@ return obj; } + @Override public PyObject __call__(PyObject self, PyObject[] args, String[] keywords) { if (self == null) { throw Py.TypeError("invalid self argument to constructor"); @@ -144,6 +145,7 @@ return Py.None; } + @Override public PyObject __call__(PyObject[] args, String[] keywords) { if (args.length < 1) { throw Py.TypeError("constructor requires self argument"); @@ -180,6 +182,15 @@ obj.javaProxy = jself; } + @Override + public PyObject _doget(PyObject container, PyObject wherefound) { + if (container == null) { + return this; + } + return new PyMethod(this, container, wherefound); + } + + @Override public String toString() { // printArgs(); return "<java constructor " + __name__ + " " + Py.idstr(this) + ">"; Modified: trunk/jython/src/org/python/core/PyReflectedFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyReflectedFunction.java 2009-10-04 20:16:12 UTC (rev 6836) +++ trunk/jython/src/org/python/core/PyReflectedFunction.java 2009-10-04 21:25:41 UTC (rev 6837) @@ -17,6 +17,9 @@ public int nargs; + /** Whether __call__ should act as if this is called as a static method. */ + private boolean calledStatically; + protected PyReflectedFunction(String name) { __name__ = name; } @@ -35,17 +38,22 @@ } } + @Override public PyObject _doget(PyObject container) { return _doget(container, null); } + @Override public PyObject _doget(PyObject container, PyObject wherefound) { + // NOTE: this calledStatically business is pretty hacky if (container == null) { - return this; + return calledStatically ? this : copyWithCalledStatically(true); } - return new PyMethod(this, container, wherefound); + return new PyMethod(calledStatically ? copyWithCalledStatically(false) : this, + container, wherefound); } + @Override public PyObject getDoc() { return __doc__; } @@ -66,6 +74,12 @@ return func; } + private PyReflectedFunction copyWithCalledStatically(boolean calledStatically) { + PyReflectedFunction copy = copy(); + copy.calledStatically = calledStatically; + return copy; + } + public boolean handles(Method method) { return handles(makeArgs(method)); } @@ -143,6 +157,7 @@ nargs = nn; } + @Override public PyObject __call__(PyObject self, PyObject[] args, String[] keywords) { ReflectedCallData callData = new ReflectedCallData(); ReflectedArgs match = null; @@ -179,14 +194,17 @@ return Py.java2py(o); } + @Override public PyObject __call__(PyObject[] args, String[] keywords) { - PyObject self = null; - /* - PyObject[] new_args = new PyObject[args.length - 1]; - System.arraycopy(args, 1, new_args, 0, new_args.length); - self = args[0]; - args = new_args; - */ + PyObject self; + if (calledStatically) { + self = null; + } else { + PyObject[] unboundArgs = new PyObject[args.length - 1]; + System.arraycopy(args, 1, unboundArgs, 0, unboundArgs.length); + self = args[0]; + args = unboundArgs; + } return __call__(self, args, keywords); } @@ -317,8 +335,8 @@ } } + @Override public String toString() { - // printArgs(); return "<java function " + __name__ + " " + Py.idstr(this) + ">"; } } Modified: trunk/jython/src/org/python/core/ReflectedArgs.java =================================================================== --- trunk/jython/src/org/python/core/ReflectedArgs.java 2009-10-04 20:16:12 UTC (rev 6836) +++ trunk/jython/src/org/python/core/ReflectedArgs.java 2009-10-04 21:25:41 UTC (rev 6837) @@ -50,12 +50,6 @@ */ if (this.isStatic) { if (self != null) { - /* - PyObject[] newArgs = new PyObject[pyArgs.length+1]; - System.arraycopy(pyArgs, 0, newArgs, 1, pyArgs.length); - newArgs[0] = self; - pyArgs = newArgs; - //*/ self = null; } } else { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-04 20:16:23
|
Revision: 6836 http://jython.svn.sourceforge.net/jython/?rev=6836&view=rev Author: fwierzbicki Date: 2009-10-04 20:16:12 +0000 (Sun, 04 Oct 2009) Log Message: ----------- Use sig for invokespecial and addMethod. 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-04 17:03:17 UTC (rev 6835) +++ trunk/jython/src/org/python/compiler/Module.java 2009-10-04 20:16:12 UTC (rev 6836) @@ -46,14 +46,14 @@ } public void get(Code c) throws IOException { - c.getstatic(module.classfile.name, name, $pyInteger); + c.getstatic(module.classfile.name, name, ci(PyInteger.class)); } public void put(Code c) throws IOException { - module.classfile.addField(name, $pyInteger, access); + module.classfile.addField(name, ci(PyInteger.class), access); c.iconst(value); c.invokestatic("org/python/core/Py", "newInteger", sig(PyInteger.class, Integer.TYPE)); - c.putstatic(module.classfile.name, name, $pyInteger); + c.putstatic(module.classfile.name, name, ci(PyInteger.class)); } @Override @@ -79,14 +79,14 @@ } public void get(Code c) throws IOException { - c.getstatic(module.classfile.name, name, $pyFloat); + c.getstatic(module.classfile.name, name, ci(PyFloat.class)); } public void put(Code c) throws IOException { - module.classfile.addField(name, $pyFloat, access); + module.classfile.addField(name, ci(PyFloat.class), access); c.ldc(new Double(value)); c.invokestatic("org/python/core/Py", "newFloat", sig(PyFloat.class, Double.TYPE)); - c.putstatic(module.classfile.name, name, $pyFloat); + c.putstatic(module.classfile.name, name, ci(PyFloat.class)); } @Override @@ -112,14 +112,14 @@ } public void get(Code c) throws IOException { - c.getstatic(module.classfile.name, name, $pyComplex); + c.getstatic(module.classfile.name, name, ci(PyComplex.class)); } public void put(Code c) throws IOException { - module.classfile.addField(name, $pyComplex, access); + module.classfile.addField(name, ci(PyComplex.class), access); c.ldc(new Double(value)); c.invokestatic("org/python/core/Py", "newImaginary", sig(PyComplex.class, Double.TYPE)); - c.putstatic(module.classfile.name, name, $pyComplex); + c.putstatic(module.classfile.name, name, ci(PyComplex.class)); } @Override @@ -145,15 +145,15 @@ } public void get(Code c) throws IOException { - c.getstatic(module.classfile.name, name, $pyStr); + c.getstatic(module.classfile.name, name, ci(PyString.class)); } public void put(Code c) throws IOException { - module.classfile.addField(name, $pyStr, access); + module.classfile.addField(name, ci(PyString.class), access); c.ldc(value); c.invokestatic("org/python/core/PyString", "fromInterned", sig(PyString.class, String.class)); - c.putstatic(module.classfile.name, name, $pyStr); + c.putstatic(module.classfile.name, name, ci(PyString.class)); } @Override @@ -179,15 +179,15 @@ } public void get(Code c) throws IOException { - c.getstatic(module.classfile.name, name, $pyUnicode); + c.getstatic(module.classfile.name, name, ci(PyUnicode.class)); } public void put(Code c) throws IOException { - module.classfile.addField(name, $pyUnicode, access); + module.classfile.addField(name, ci(PyUnicode.class), access); c.ldc(value); c.invokestatic("org/python/core/PyUnicode", "fromInterned", sig(PyUnicode.class, String.class)); - c.putstatic(module.classfile.name, name, $pyUnicode); + c.putstatic(module.classfile.name, name, ci(PyUnicode.class)); } @Override @@ -213,14 +213,14 @@ } public void get(Code c) throws IOException { - c.getstatic(module.classfile.name, name, $pyLong); + c.getstatic(module.classfile.name, name, ci(PyLong.class)); } public void put(Code c) throws IOException { - module.classfile.addField(name, $pyLong, access); + module.classfile.addField(name, ci(PyLong.class), access); c.ldc(value); c.invokestatic("org/python/core/Py", "newLong", sig(PyLong.class, String.class)); - c.putstatic(module.classfile.name, name, $pyLong); + c.putstatic(module.classfile.name, name, ci(PyLong.class)); } @Override @@ -257,11 +257,11 @@ } public void get(Code c) throws IOException { - c.getstatic(module.classfile.name, name, $pyCode); + c.getstatic(module.classfile.name, name, ci(PyCode.class)); } public void put(Code c) throws IOException { - module.classfile.addField(name, $pyCode, access); + module.classfile.addField(name, ci(PyCode.class), access); c.iconst(argcount); //Make all names @@ -305,7 +305,7 @@ String[].class, String.class, String.class, Integer.TYPE, Boolean.TYPE, Boolean.TYPE, PyFunctionTable.class, Integer.TYPE, String[].class, String[].class, Integer.TYPE, Integer.TYPE)); - c.putstatic(module.classfile.name, name, $pyCode); + c.putstatic(module.classfile.name, name, ci(PyCode.class)); } } @@ -449,7 +449,7 @@ Code c = classfile.addMethod( code.fname, - "(" + $pyFrame + $threadState + ")" + $pyObj, + sig(PyObject.class, PyFrame.class, ThreadState.class), ACC_PUBLIC); CodeCompiler compiler = new CodeCompiler(this, printResults); @@ -541,25 +541,25 @@ //This block of code writes out the various standard methods public void addInit() throws IOException { - Code c = classfile.addMethod("<init>", "(Ljava/lang/String;)V", ACC_PUBLIC); + Code c = classfile.addMethod("<init>", sig(Void.TYPE, String.class), ACC_PUBLIC); c.aload(0); - c.invokespecial("org/python/core/PyFunctionTable", "<init>", "()V"); + c.invokespecial("org/python/core/PyFunctionTable", "<init>", sig(Void.TYPE)); addConstants(c); } public void addRunnable() throws IOException { - Code c = classfile.addMethod("getMain", "()" + $pyCode, ACC_PUBLIC); + Code c = classfile.addMethod("getMain", sig(PyCode.class), ACC_PUBLIC); mainCode.get(c); c.areturn(); } public void addMain() throws IOException { - Code c = classfile.addMethod("main", "(" + $strArr + ")V", + Code c = classfile.addMethod("main", sig(Void.TYPE, String[].class), ACC_PUBLIC | ACC_STATIC); c.new_(classfile.name); c.dup(); c.ldc(classfile.name); - c.invokespecial(classfile.name, "<init>", "(" + $str + ")V"); + 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, @@ -571,7 +571,7 @@ public void addBootstrap() throws IOException { Code c = classfile.addMethod(CodeLoader.GET_BOOTSTRAP_METHOD_NAME, - "()" + Type.getDescriptor(CodeBootstrap.class), + sig(CodeBootstrap.class), ACC_PUBLIC | ACC_STATIC); c.ldc(Type.getType("L" + classfile.name + ";")); c.invokestatic(p(PyRunnableBootstrap.class), PyRunnableBootstrap.REFLECTION_METHOD_NAME, @@ -602,7 +602,7 @@ public void addFunctions() throws IOException { Code code = classfile.addMethod( "call_function", - "(I" + $pyFrame + $threadState + ")" + $pyObj, + sig(PyObject.class, Integer.TYPE, PyFrame.class, ThreadState.class), ACC_PUBLIC); code.aload(0); // this This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-04 17:03:29
|
Revision: 6835 http://jython.svn.sourceforge.net/jython/?rev=6835&view=rev Author: fwierzbicki Date: 2009-10-04 17:03:17 +0000 (Sun, 04 Oct 2009) Log Message: ----------- use sig for invokestatic. 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-04 15:10:21 UTC (rev 6834) +++ trunk/jython/src/org/python/compiler/Module.java 2009-10-04 17:03:17 UTC (rev 6835) @@ -19,10 +19,17 @@ import org.python.core.ThreadState; import org.python.core.Py; import org.python.core.PyCode; +import org.python.core.PyComplex; +import org.python.core.PyException; +import org.python.core.PyFloat; import org.python.core.PyFrame; +import org.python.core.PyFunctionTable; +import org.python.core.PyInteger; +import org.python.core.PyLong; import org.python.core.PyObject; -import org.python.core.PyException; import org.python.core.PyRunnableBootstrap; +import org.python.core.PyString; +import org.python.core.PyUnicode; import org.objectweb.asm.Type; import org.python.antlr.ParseException; import org.python.antlr.PythonTree; @@ -45,7 +52,7 @@ public void put(Code c) throws IOException { module.classfile.addField(name, $pyInteger, access); c.iconst(value); - c.invokestatic("org/python/core/Py", "newInteger", "(I)" + $pyInteger); + c.invokestatic("org/python/core/Py", "newInteger", sig(PyInteger.class, Integer.TYPE)); c.putstatic(module.classfile.name, name, $pyInteger); } @@ -78,7 +85,7 @@ public void put(Code c) throws IOException { module.classfile.addField(name, $pyFloat, access); c.ldc(new Double(value)); - c.invokestatic("org/python/core/Py", "newFloat", "(D)" + $pyFloat); + c.invokestatic("org/python/core/Py", "newFloat", sig(PyFloat.class, Double.TYPE)); c.putstatic(module.classfile.name, name, $pyFloat); } @@ -111,7 +118,7 @@ public void put(Code c) throws IOException { module.classfile.addField(name, $pyComplex, access); c.ldc(new Double(value)); - c.invokestatic("org/python/core/Py", "newImaginary", "(D)" + $pyComplex); + c.invokestatic("org/python/core/Py", "newImaginary", sig(PyComplex.class, Double.TYPE)); c.putstatic(module.classfile.name, name, $pyComplex); } @@ -144,7 +151,8 @@ public void put(Code c) throws IOException { module.classfile.addField(name, $pyStr, access); c.ldc(value); - c.invokestatic("org/python/core/PyString", "fromInterned", "(" + $str + ")" + $pyStr); + c.invokestatic("org/python/core/PyString", "fromInterned", sig(PyString.class, + String.class)); c.putstatic(module.classfile.name, name, $pyStr); } @@ -177,7 +185,8 @@ public void put(Code c) throws IOException { module.classfile.addField(name, $pyUnicode, access); c.ldc(value); - c.invokestatic("org/python/core/PyUnicode", "fromInterned", "(" + $str + ")" + $pyUnicode); + c.invokestatic("org/python/core/PyUnicode", "fromInterned", sig(PyUnicode.class, + String.class)); c.putstatic(module.classfile.name, name, $pyUnicode); } @@ -210,7 +219,7 @@ public void put(Code c) throws IOException { module.classfile.addField(name, $pyLong, access); c.ldc(value); - c.invokestatic("org/python/core/Py", "newLong", "(" + $str + ")" + $pyLong); + c.invokestatic("org/python/core/Py", "newLong", sig(PyLong.class, String.class)); c.putstatic(module.classfile.name, name, $pyLong); } @@ -292,7 +301,10 @@ c.iconst(moreflags); - c.invokestatic("org/python/core/Py", "newCode", "(I" + $strArr + $str + $str + "IZZ" + $pyFuncTbl + "I" + $strArr + $strArr + "II)" + $pyCode); + c.invokestatic("org/python/core/Py", "newCode", sig(PyCode.class, Integer.TYPE, + String[].class, String.class, String.class, Integer.TYPE, Boolean.TYPE, + Boolean.TYPE, PyFunctionTable.class, Integer.TYPE, String[].class, + String[].class, Integer.TYPE, Integer.TYPE)); c.putstatic(module.classfile.name, name, $pyCode); } } @@ -550,11 +562,10 @@ c.invokespecial(classfile.name, "<init>", "(" + $str + ")V"); c.invokevirtual(classfile.name, "getMain", sig(PyCode.class)); String bootstrap = Type.getDescriptor(CodeBootstrap.class); - c.invokestatic(Type.getInternalName(CodeLoader.class), - CodeLoader.SIMPLE_FACTORY_METHOD_NAME, - "(" + $pyCode + ")" + bootstrap); + c.invokestatic(p(CodeLoader.class), CodeLoader.SIMPLE_FACTORY_METHOD_NAME, + sig(CodeBootstrap.class, PyCode.class)); c.aload(0); - c.invokestatic("org/python/core/Py", "runMain", "(" + bootstrap + $strArr + ")V"); + c.invokestatic(p(Py.class), "runMain", sig(Void.TYPE, CodeBootstrap.class, String[].class)); c.return_(); } @@ -563,9 +574,8 @@ "()" + Type.getDescriptor(CodeBootstrap.class), ACC_PUBLIC | ACC_STATIC); c.ldc(Type.getType("L" + classfile.name + ";")); - c.invokestatic(Type.getInternalName(PyRunnableBootstrap.class), - PyRunnableBootstrap.REFLECTION_METHOD_NAME, - "(" + $clss + ")" + Type.getDescriptor(CodeBootstrap.class)); + c.invokestatic(p(PyRunnableBootstrap.class), PyRunnableBootstrap.REFLECTION_METHOD_NAME, + sig(CodeBootstrap.class, Class.class)); c.areturn(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-04 15:10:28
|
Revision: 6834 http://jython.svn.sourceforge.net/jython/?rev=6834&view=rev Author: fwierzbicki Date: 2009-10-04 15:10:21 +0000 (Sun, 04 Oct 2009) Log Message: ----------- Use sig for invokevirtual. 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-04 14:39:40 UTC (rev 6833) +++ trunk/jython/src/org/python/compiler/Module.java 2009-10-04 15:10:21 UTC (rev 6834) @@ -16,7 +16,11 @@ import org.python.core.CodeFlag; import org.python.core.CodeLoader; import org.python.core.CompilerFlags; +import org.python.core.ThreadState; import org.python.core.Py; +import org.python.core.PyCode; +import org.python.core.PyFrame; +import org.python.core.PyObject; import org.python.core.PyException; import org.python.core.PyRunnableBootstrap; import org.objectweb.asm.Type; @@ -24,6 +28,7 @@ import org.python.antlr.PythonTree; import org.python.antlr.ast.Suite; import org.python.antlr.base.mod; +import static org.python.util.CodegenUtils.*; class PyIntegerConstant extends Constant implements ClassConstants, Opcodes { @@ -444,9 +449,11 @@ c.aload(1); c.ldc("__name__"); - c.invokevirtual("org/python/core/PyFrame", "getname", "(" + $str + ")" + $pyObj); + c.invokevirtual("org/python/core/PyFrame", "getname", sig(PyObject.class, + String.class)); - c.invokevirtual("org/python/core/PyFrame", "setlocal", "(" + $str + $pyObj + ")V"); + c.invokevirtual("org/python/core/PyFrame", "setlocal", sig(Void.TYPE, String.class, + PyObject.class)); } Label genswitch = new Label(); @@ -469,7 +476,8 @@ SymInfo syminf = tbl.get(paramcells.get(i)); c.iconst(syminf.locals_index); c.iconst(syminf.env_index); - c.invokevirtual("org/python/core/PyFrame", "to_cell", "(II)V"); + c.invokevirtual("org/python/core/PyFrame", "to_cell", sig(Void.TYPE, Integer.TYPE, + Integer.TYPE)); } } @@ -540,7 +548,7 @@ c.dup(); c.ldc(classfile.name); c.invokespecial(classfile.name, "<init>", "(" + $str + ")V"); - c.invokevirtual(classfile.name, "getMain", "()" + $pyCode); + c.invokevirtual(classfile.name, "getMain", sig(PyCode.class)); String bootstrap = Type.getDescriptor(CodeBootstrap.class); c.invokestatic(Type.getInternalName(CodeLoader.class), CodeLoader.SIMPLE_FACTORY_METHOD_NAME, @@ -601,7 +609,8 @@ code.tableswitch(0, labels.length - 1, def, labels); for(i=0; i<labels.length; i++) { code.label(labels[i]); - code.invokevirtual(classfile.name, (codes.get(i)).fname, "(" + $pyFrame + $threadState + ")" + $pyObj); + code.invokevirtual(classfile.name, (codes.get(i)).fname, sig(PyObject.class, + PyFrame.class, ThreadState.class)); code.areturn(); } code.label(def); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-04 14:39:46
|
Revision: 6833 http://jython.svn.sourceforge.net/jython/?rev=6833&view=rev Author: fwierzbicki Date: 2009-10-04 14:39:40 +0000 (Sun, 04 Oct 2009) Log Message: ----------- Finish up CodeCompiler conversion to CodegenUtils. 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-04 14:10:58 UTC (rev 6832) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-04 14:39:40 UTC (rev 6833) @@ -183,7 +183,7 @@ } private void loadf_back() throws Exception { - code.getfield(p(PyFrame.class), "f_back", $pyFrame); + code.getfield(p(PyFrame.class), "f_back", ci(PyFrame.class)); } public int storeTop() throws Exception { @@ -283,7 +283,7 @@ loadFrame(); code.iconst(scope.max_with_count); code.anewarray(p(PyObject.class)); - code.putfield(p(PyFrame.class), "f_exits", $pyObjArr); + code.putfield(p(PyFrame.class), "f_exits", ci(PyObject[].class)); } Object exit = visit(node); @@ -345,9 +345,9 @@ else n = nodes.size(); - int array = code.getLocal("[Lorg/python/core/PyObject;"); + int array = code.getLocal(ci(PyObject[].class)); if (n == 0) { - code.getstatic(p(Py.class), "EmptyObjects", $pyObjArr); + code.getstatic(p(Py.class), "EmptyObjects", ci(PyObject[].class)); code.astore(array); } else { code.iconst(n); @@ -389,7 +389,7 @@ int n = scope.freevars.size(); if (n == 0) return false; - int tmp = code.getLocal("[Lorg/python/core/PyObject;"); + int tmp = code.getLocal(ci(PyObject[].class)); code.iconst(n); code.anewarray(p(PyObject.class)); code.astore(tmp); @@ -647,7 +647,7 @@ private int saveStack() throws Exception { if (stack.size() > 0) { - int array = code.getLocal("[Ljava/lang/Object;"); + int array = code.getLocal(ci(Object[].class)); code.iconst(stack.size()); code.anewarray(p(Object.class)); code.astore(array); @@ -700,9 +700,9 @@ Vector<String> v = code.getActiveLocals(); loadFrame(); - code.getfield(p(PyFrame.class), "f_savedlocals", "[Ljava/lang/Object;"); + code.getfield(p(PyFrame.class), "f_savedlocals", ci(Object[].class)); - int locals = code.getLocal("[Ljava/lang/Object;"); + int locals = code.getLocal(ci(Object[].class)); code.astore(locals); for (int i = 0; i < v.size(); i++) { @@ -751,7 +751,7 @@ Vector<String> v = code.getActiveLocals(); code.iconst(v.size()); code.anewarray(p(Object.class)); - int locals = code.getLocal("[Ljava/lang/Object;"); + int locals = code.getLocal(ci(Object[].class)); code.astore(locals); for (int i = 0; i < v.size(); i++) { @@ -770,7 +770,7 @@ loadFrame(); code.aload(locals); - code.putfield(p(PyFrame.class), "f_savedlocals", "[Ljava/lang/Object;"); + code.putfield(p(PyFrame.class), "f_savedlocals", ci(Object[].class)); code.freeLocal(locals); } @@ -1553,7 +1553,7 @@ c.iconst_0(); } c.anewarray(p(String.class)); - int strings = c.getLocal("[Ljava/lang/String;"); + int strings = c.getLocal(ci(String[].class)); c.astore(strings); if (names != null) { int i = 0; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-04 14:11:05
|
Revision: 6832 http://jython.svn.sourceforge.net/jython/?rev=6832&view=rev Author: fwierzbicki Date: 2009-10-04 14:10:58 +0000 (Sun, 04 Oct 2009) Log Message: ----------- Use sig() for invokestatic calls. 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-04 02:42:47 UTC (rev 6831) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-04 14:10:58 UTC (rev 6832) @@ -370,7 +370,7 @@ public void freeArray(int array) { code.aload(array); code.aconst_null(); - code.invokestatic(p(Arrays.class), "fill", "(" + $objArr + $obj + ")V"); + code.invokestatic(p(Arrays.class), "fill", sig(Void.TYPE, Object[].class, Object.class)); code.freeLocal(array); } @@ -479,7 +479,7 @@ visit(node.getInternalValue()); if (print_results) { - code.invokestatic(p(Py.class), "printResult", "(" + $pyObj + ")V"); + code.invokestatic(p(Py.class), "printResult", sig(Void.TYPE, PyObject.class)); } else { code.pop(); } @@ -514,9 +514,9 @@ if (node.getInternalValues() == null || node.getInternalValues().size() == 0) { if (node.getInternalDest() != null) { code.aload(tmp); - code.invokestatic(p(Py.class), "printlnv", "(" + $pyObj + ")V"); + code.invokestatic(p(Py.class), "printlnv", sig(Void.TYPE, PyObject.class)); } else { - code.invokestatic(p(Py.class), "println", "()V"); + code.invokestatic(p(Py.class), "println", sig(Void.TYPE)); } } else { for (int i = 0; i < node.getInternalValues().size(); i++) { @@ -524,16 +524,19 @@ code.aload(tmp); visit(node.getInternalValues().get(i)); if (node.getInternalNl() && i == node.getInternalValues().size() - 1) { - code.invokestatic(p(Py.class), "println", "(" + $pyObj + $pyObj + ")V"); + code.invokestatic(p(Py.class), "println", sig(Void.TYPE, PyObject.class, + PyObject.class)); } else { - code.invokestatic(p(Py.class), "printComma", "(" + $pyObj + $pyObj + ")V"); + code.invokestatic(p(Py.class), "printComma", sig(Void.TYPE, PyObject.class, + PyObject.class)); } } else { visit(node.getInternalValues().get(i)); if (node.getInternalNl() && i == node.getInternalValues().size() - 1) { - code.invokestatic(p(Py.class), "println", "(" + $pyObj + ")V"); + code.invokestatic(p(Py.class), "println", sig(Void.TYPE, PyObject.class)); } else { - code.invokestatic(p(Py.class), "printComma", "(" + $pyObj + ")V"); + code.invokestatic(p(Py.class), "printComma", sig(Void.TYPE, + PyObject.class)); } } @@ -811,16 +814,18 @@ if (node.getInternalInst() != null) { visit(node.getInternalInst()); stackProduce(); } if (node.getInternalTback() != null) { visit(node.getInternalTback()); stackProduce(); } if (node.getInternalType() == null) { - code.invokestatic(p(Py.class), "makeException", "()" + $pyExc); + code.invokestatic(p(Py.class), "makeException", sig(PyException.class)); } else if (node.getInternalInst() == null) { stackConsume(); - code.invokestatic(p(Py.class), "makeException", "(" + $pyObj + ")" + $pyExc); + code.invokestatic(p(Py.class), "makeException", sig(PyException.class, PyObject.class)); } else if (node.getInternalTback() == null) { stackConsume(2); - code.invokestatic(p(Py.class), "makeException", "(" + $pyObj + $pyObj + ")" + $pyExc); + code.invokestatic(p(Py.class), "makeException", sig(PyException.class, PyObject.class, + PyObject.class)); } else { stackConsume(3); - code.invokestatic(p(Py.class), "makeException", "(" + $pyObj + $pyObj + $pyObj + ")" + $pyExc); + code.invokestatic(p(Py.class), "makeException", sig(PyException.class, PyObject.class, + PyObject.class, PyObject.class)); } code.athrow(); return Exit; @@ -836,7 +841,8 @@ asname = a.getInternalAsname(); code.ldc(name); loadFrame(); - code.invokestatic(p(imp.class), "importOneAs", "(" + $str + $pyFrame + ")" + $pyObj); + code.invokestatic(p(imp.class), "importOneAs", sig(PyObject.class, String.class, + PyFrame.class)); } else { String name = a.getInternalName(); asname = name; @@ -844,7 +850,8 @@ asname = asname.substring(0, asname.indexOf('.')); code.ldc(name); loadFrame(); - code.invokestatic(p(imp.class), "importOne", "(" + $str + $pyFrame + ")" + $pyObj); + code.invokestatic(p(imp.class), "importOne", sig(PyObject.class, String.class, + PyFrame.class)); } set(new Name(a, asname, expr_contextType.Store)); } @@ -882,7 +889,8 @@ } loadFrame(); - code.invokestatic(p(imp.class), "importAll", "(" + $str + $pyFrame + ")V"); + code.invokestatic(p(imp.class), "importAll", sig(Void.TYPE, String.class, + PyFrame.class)); } else { java.util.List<String> fromNames = new ArrayList<String>();//[names.size()]; java.util.List<String> asnames = new ArrayList<String>();//[names.size()]; @@ -907,7 +915,8 @@ } else { code.iconst(node.getInternalLevel()); } - code.invokestatic(p(imp.class), "importFrom", "(" + $str + $strArr + $pyFrame + "I" + ")" + $pyObjArr); + code.invokestatic(p(imp.class), "importFrom", sig(PyObject[].class, String.class, + String[].class, PyFrame.class, Integer.TYPE)); int tmp = storeTop(); for (int i = 0; i < aliases.size(); i++) { code.aload(tmp); @@ -947,7 +956,8 @@ //do the real work here stackConsume(3); - code.invokestatic(p(Py.class), "exec", "(" + $pyObj + $pyObj + $pyObj + ")V"); + code.invokestatic(p(Py.class), "exec", sig(Void.TYPE, PyObject.class, PyObject.class, + PyObject.class)); return null; } @@ -986,8 +996,8 @@ code.swap(); // The type is the first argument, but the message could be a yield - code.invokestatic(p(Py.class), "makeException", "(" + $pyObj + $pyObj + ")" + $pyExc); - + code.invokestatic(p(Py.class), "makeException", sig(PyException.class, PyObject.class, + PyObject.class)); /* Raise assertion error. Only executes this logic if assertion failed */ code.athrow(); @@ -1246,7 +1256,8 @@ code.aload(excLocal); loadFrame(); - code.invokestatic(p(Py.class), "addTraceback", "(" + $throwable + $pyFrame + ")V"); + code.invokestatic(p(Py.class), "addTraceback", sig(Void.TYPE, Throwable.class, + PyFrame.class)); inlineFinally(inFinally); code.aload(excLocal); @@ -1327,7 +1338,8 @@ loadFrame(); - code.invokestatic(p(Py.class), "setException", "(" + $throwable + $pyFrame + ")" + $pyExc); + code.invokestatic(p(Py.class), "setException", sig(PyException.class, Throwable.class, + PyFrame.class)); int exc = code.getFinallyLocal(p(Throwable.class)); code.astore(exc); @@ -1866,7 +1878,8 @@ public Object seqSet(java.util.List<expr> nodes) throws Exception { code.aload(temporary); code.iconst(nodes.size()); - code.invokestatic(p(Py.class), "unpackSequence", "(" + $pyObj + "I)" + $pyObjArr); + code.invokestatic(p(Py.class), "unpackSequence", sig(PyObject[].class, PyObject.class, + Integer.TYPE)); int tmp = code.getLocal("[org/python/core/PyObject"); code.astore(tmp); @@ -2082,9 +2095,11 @@ //Make class out of name, bases, and code if (!makeClosure(scope)) { - code.invokestatic(p(Py.class), "makeClass", "(" + $str + $pyObjArr + $pyCode + $pyObj + ")" + $pyObj); + code.invokestatic(p(Py.class), "makeClass", sig(PyObject.class, String.class, + PyObject[].class, PyCode.class, PyObject.class)); } else { - code.invokestatic(p(Py.class), "makeClass", "(" + $str + $pyObjArr + $pyCode + $pyObj + $pyObjArr + ")" + $pyObj); + code.invokestatic(p(Py.class), "makeClass", sig(PyObject.class, String.class, + PyObject[].class, PyCode.class, PyObject.class, PyObject[].class)); } applyDecorators(node.getInternalDecorator_list()); @@ -2327,15 +2342,20 @@ final Label label_catch = new Label(); final Label label_end = new Label(); - final Method contextGuard_getManager = Method.getMethod("org.python.core.ContextManager getManager (org.python.core.PyObject)"); - final Method __enter__ = Method.getMethod("org.python.core.PyObject __enter__ (org.python.core.ThreadState)"); - final Method __exit__ = Method.getMethod("boolean __exit__ (org.python.core.ThreadState,org.python.core.PyException)"); + final Method contextGuard_getManager = Method.getMethod( + "org.python.core.ContextManager getManager (org.python.core.PyObject)"); + final Method __enter__ = Method.getMethod( + "org.python.core.PyObject __enter__ (org.python.core.ThreadState)"); + final Method __exit__ = Method.getMethod( + "boolean __exit__ (org.python.core.ThreadState,org.python.core.PyException)"); // mgr = (EXPR) visit(node.getInternalContext_expr()); - // wrap the manager with the ContextGuard (or get it directly if it supports the ContextManager interface) - code.invokestatic(Type.getType(ContextGuard.class).getInternalName(), contextGuard_getManager.getName(), contextGuard_getManager.getDescriptor()); + // wrap the manager with the ContextGuard (or get it directly if it + // supports the ContextManager interface) + code.invokestatic(Type.getType(ContextGuard.class).getInternalName(), + contextGuard_getManager.getName(), contextGuard_getManager.getDescriptor()); code.dup(); @@ -2344,7 +2364,8 @@ // value = mgr.__enter__() loadThreadState(); - code.invokeinterface(Type.getType(ContextManager.class).getInternalName(), __enter__.getName(), __enter__.getDescriptor()); + code.invokeinterface(Type.getType(ContextManager.class).getInternalName(), + __enter__.getName(), __enter__.getDescriptor()); int value_tmp = code.getLocal(p(PyObject.class)); code.astore(value_tmp); @@ -2403,12 +2424,14 @@ code.label(label_catch); loadFrame(); - code.invokestatic(p(Py.class), "setException", "(" + $throwable + $pyFrame + ")" + $pyExc); + code.invokestatic(p(Py.class), "setException", sig(PyException.class, Throwable.class, + PyFrame.class)); code.aload(mgr_tmp); code.swap(); loadThreadState(); code.swap(); - code.invokeinterface(Type.getType(ContextManager.class).getInternalName(), __exit__.getName(), __exit__.getDescriptor()); + code.invokeinterface(Type.getType(ContextManager.class).getInternalName(), + __exit__.getName(), __exit__.getDescriptor()); // # The exceptional case is handled here // exc = False # implicit @@ -2416,7 +2439,7 @@ code.ifne(label_end); // raise // # The exception is swallowed if exit() returns true - code.invokestatic(p(Py.class), "makeException", "()Lorg/python/core/PyException;"); + code.invokestatic(p(Py.class), "makeException", sig(PyException.class)); code.checkcast(p(Throwable.class)); code.athrow(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-04 03:14:43
|
Revision: 6831 http://jython.svn.sourceforge.net/jython/?rev=6831&view=rev Author: fwierzbicki Date: 2009-10-04 02:42:47 +0000 (Sun, 04 Oct 2009) Log Message: ----------- Fix all invokevirtual to use sig() -- fix some invokespecial lines that went over 100 chars as per coding conventions. 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-04 01:16:45 UTC (rev 6830) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-04 02:42:47 UTC (rev 6831) @@ -197,7 +197,7 @@ code.setline(line); loadFrame(); code.iconst(line); - code.invokevirtual(p(PyFrame.class), "setline", "(I)V"); + code.invokevirtual(p(PyFrame.class), "setline", sig(Void.TYPE, Integer.TYPE)); } } @@ -319,7 +319,8 @@ loadFrame(); code.ldc("__doc__"); visit(((Expr) suite.getInternalBody().get(0)).getInternalValue()); - code.invokevirtual(p(PyFrame.class), "setglobal", "(" +$str + $pyObj + ")V"); + code.invokevirtual(p(PyFrame.class), "setglobal", sig(Void.TYPE, String.class, + PyObject.class)); } traverse(suite); return null; @@ -402,7 +403,7 @@ } SymInfo symInfo = upTbl.get(scope.freevars.elementAt(i)); code.iconst(symInfo.env_index); - code.invokevirtual(p(PyFrame.class), "getclosure", "(I)" + $pyObj); + code.invokevirtual(p(PyFrame.class), "getclosure", sig(PyObject.class, Integer.TYPE)); code.aastore(); } @@ -440,9 +441,11 @@ getDocString(node.getInternalBody()); if (!makeClosure(scope)) { - code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class, PyObject.class)); + code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, + PyObject[].class, PyCode.class, PyObject.class)); } else { - code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class, PyObject.class, PyObject[].class)); + code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, + PyObject[].class, PyCode.class, PyObject.class, PyObject[].class)); } applyDecorators(node.getInternalDecorator_list()); @@ -461,7 +464,8 @@ stackConsume(); loadThreadState(); code.aload(res); - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class, PyObject.class)); code.astore(res); } code.aload(res); @@ -607,7 +611,7 @@ restoreStack(stackState); loadFrame(); - code.invokevirtual(p(PyFrame.class), "getGeneratorInput", "()" + $obj); + code.invokevirtual(p(PyFrame.class), "getGeneratorInput", sig(Object.class)); code.dup(); code.instanceof_(p(PyException.class)); Label done2 = new Label(); @@ -956,7 +960,7 @@ loadFrame(); emitGetGlobal("__debug__"); - code.invokevirtual(p(PyObject.class), "__nonzero__", "()Z"); + code.invokevirtual(p(PyObject.class), "__nonzero__", sig(Boolean.TYPE)); code.ifeq(end_of_assert); @@ -964,7 +968,7 @@ then the assertion succeeded, the message portion should not be processed. Otherwise, the message will be processed. */ visit(node.getInternalTest()); - code.invokevirtual(p(PyObject.class), "__nonzero__", "()Z"); + code.invokevirtual(p(PyObject.class), "__nonzero__", sig(Boolean.TYPE)); /* If evaluation is false, then branch to end of method */ code.ifne(end_of_assert); @@ -1001,7 +1005,7 @@ setline(node.getInternalTest()); visit(node.getInternalTest()); - code.invokevirtual(p(PyObject.class), "__nonzero__", "()Z"); + code.invokevirtual(p(PyObject.class), "__nonzero__", sig(Boolean.TYPE)); code.ifeq(end_of_suite); @@ -1038,7 +1042,7 @@ Label end_of_else = new Label(); visit(node.getInternalTest()); - code.invokevirtual(p(PyObject.class), "__nonzero__", "()Z"); + code.invokevirtual(p(PyObject.class), "__nonzero__", sig(Boolean.TYPE)); code.ifeq(end_of_else); visit(node.getInternalBody()); @@ -1086,7 +1090,7 @@ //Do test visit(node.getInternalTest()); - code.invokevirtual(p(PyObject.class), "__nonzero__", "()Z"); + code.invokevirtual(p(PyObject.class), "__nonzero__", sig(Boolean.TYPE)); code.ifne(start_loop); finishLoop(savebcf); @@ -1118,7 +1122,7 @@ int expr_tmp = code.getLocal(p(PyObject.class)); //set up the loop iterator - code.invokevirtual(p(PyObject.class), "__iter__", "()Lorg/python/core/PyObject;"); + code.invokevirtual(p(PyObject.class), "__iter__", sig(PyObject.class)); code.astore(iter_tmp); //do check at end of loop. Saves one opcode ;-) @@ -1137,7 +1141,7 @@ setline(node); //get the next element from the list code.aload(iter_tmp); - code.invokevirtual(p(PyObject.class), "__iternext__", "()" + $pyObj); + code.invokevirtual(p(PyObject.class), "__iternext__", sig(PyObject.class)); code.astore(expr_tmp); code.aload(expr_tmp); @@ -1174,7 +1178,8 @@ code.aload(exc); //get specific exception visit(handler.getInternalType()); - code.invokevirtual(p(PyException.class), "match", "(" + $pyObj + ")Z"); + code.invokevirtual(p(PyException.class), "match", sig(Boolean.TYPE, + PyObject.class)); code.ifeq(end_of_self); } else { if (i != node.getInternalHandlers().size()-1) { @@ -1367,7 +1372,7 @@ visit(node.getInternalValues().get(0)); for (int i = 1; i < node.getInternalValues().size(); i++) { code.dup(); - code.invokevirtual(p(PyObject.class), "__nonzero__", "()Z"); + code.invokevirtual(p(PyObject.class), "__nonzero__", sig(Boolean.TYPE)); switch (node.getInternalOp()) { case Or : code.ifne(end); @@ -1403,7 +1408,7 @@ visitCmpop(node.getInternalOps().get(i)); code.dup(); code.astore(result); - code.invokevirtual(p(PyObject.class), "__nonzero__", "()Z"); + code.invokevirtual(p(PyObject.class), "__nonzero__", sig(Boolean.TYPE)); code.ifeq(end); } @@ -1439,7 +1444,7 @@ case In: name = "_in"; break; case NotIn: name = "_notin"; break; } - code.invokevirtual(p(PyObject.class), name, "(" + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), name, sig(PyObject.class, PyObject.class)); } @Override @@ -1467,7 +1472,7 @@ if (node.getInternalOp() == operatorType.Div && module.getFutures().areDivisionOn()) { name = "_truediv"; } - code.invokevirtual(p(PyObject.class), name, "(" + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), name, sig(PyObject.class, PyObject.class)); return null; } @@ -1481,7 +1486,7 @@ case UAdd: name = "__pos__"; break; case USub: name = "__neg__"; break; } - code.invokevirtual(p(PyObject.class), name, "()" + $pyObj); + code.invokevirtual(p(PyObject.class), name, sig(PyObject.class)); return null; } @@ -1515,7 +1520,7 @@ if (node.getInternalOp() == operatorType.Div && module.getFutures().areDivisionOn()) { name = "_itruediv"; } - code.invokevirtual(p(PyObject.class), name, "(" + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), name, sig(PyObject.class, PyObject.class)); code.freeLocal(target); temporary = storeTop(); @@ -1557,31 +1562,34 @@ String name = getName(node.getInternalAttr()); visit(node.getInternalValue()); stackProduce(); code.ldc(name); - code.invokevirtual(p(PyObject.class), "__getattr__", "(" + $str + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__getattr__", sig(PyObject.class, String.class)); loadThreadState(); stackProduce(p(ThreadState.class)); switch (values.size()) { case 0: stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class)); break; case 1: visit(values.get(0)); stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, + PyObject.class)); break; case 2: visit(values.get(0)); stackProduce(); visit(values.get(1)); stackConsume(3); // target + ts + arguments - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObj + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, + PyObject.class, PyObject.class)); break; case 3: visit(values.get(0)); stackProduce(); visit(values.get(1)); stackProduce(); visit(values.get(2)); stackConsume(4); // target + ts + arguments - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObj + $pyObj + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, + PyObject.class, PyObject.class, PyObject.class)); break; case 4: visit(values.get(0)); stackProduce(); @@ -1589,14 +1597,16 @@ visit(values.get(2)); stackProduce(); visit(values.get(3)); stackConsume(5); // target + ts + arguments - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObj + $pyObj + $pyObj + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, + PyObject.class, PyObject.class, PyObject.class, PyObject.class)); break; default: int argArray = makeArray(values); code.aload(argArray); code.freeLocal(argArray); stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObjArr + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, + PyObject[].class)); break; } return null; @@ -1646,7 +1656,8 @@ stackConsume(3); // target + starargs + kwargs - code.invokevirtual(p(PyObject.class), "_callextra", "(" + $pyObjArr + $strArr + $pyObj + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "_callextra", sig(PyObject.class, + PyObject[].class, String[].class, PyObject.class, PyObject.class)); } else if (keys.size() > 0) { loadThreadState(); stackProduce(p(ThreadState.class)); int argArray = makeArray(values); @@ -1656,31 +1667,36 @@ code.freeLocal(argArray); code.freeLocal(strArray); stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObjArr + $strArr + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, + PyObject[].class, String[].class)); } else { loadThreadState(); stackProduce(p(ThreadState.class)); switch (values.size()) { case 0: stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class)); break; case 1: visit(values.get(0)); stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class, PyObject.class)); break; case 2: visit(values.get(0)); stackProduce(); visit(values.get(1)); stackConsume(3); // target + ts + arguments - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObj + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class, PyObject.class, PyObject.class)); break; case 3: visit(values.get(0)); stackProduce(); visit(values.get(1)); stackProduce(); visit(values.get(2)); stackConsume(4); // target + ts + arguments - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObj + $pyObj + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class, PyObject.class, PyObject.class, PyObject.class)); break; case 4: visit(values.get(0)); stackProduce(); @@ -1688,14 +1704,17 @@ visit(values.get(2)); stackProduce(); visit(values.get(3)); stackConsume(5); // target + ts + arguments - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObj + $pyObj + $pyObj + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class, PyObject.class, PyObject.class, PyObject.class, + PyObject.class)); break; default: int argArray = makeArray(values); code.aload(argArray); code.freeLocal(argArray); stackConsume(2); // target + ts - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObjArr + ")" + $pyObj);// freeArray(argArray); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, + ThreadState.class, PyObject[].class)); break; } } @@ -1736,15 +1755,18 @@ switch (ctx) { case Del: - code.invokevirtual(p(PyObject.class), "__delslice__", "(" + $pyObj + $pyObj + $pyObj + ")V"); + code.invokevirtual(p(PyObject.class), "__delslice__", sig(Void.TYPE, PyObject.class, + PyObject.class, PyObject.class)); return null; case Load: - code.invokevirtual(p(PyObject.class), "__getslice__", "(" + $pyObj + $pyObj + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__getslice__", sig(PyObject.class, + PyObject.class, PyObject.class, PyObject.class)); return null; case Param: case Store: code.aload(temporary); - code.invokevirtual(p(PyObject.class), "__setslice__", "(" + $pyObj + $pyObj + $pyObj + $pyObj + ")V"); + code.invokevirtual(p(PyObject.class), "__setslice__", sig(Void.TYPE, PyObject.class, + PyObject.class, PyObject.class, PyObject.class)); return null; } return null; @@ -1775,15 +1797,16 @@ switch (ctx) { case Del: - code.invokevirtual(p(PyObject.class), "__delitem__", "(" + $pyObj + ")V"); + code.invokevirtual(p(PyObject.class), "__delitem__", sig(Void.TYPE, PyObject.class)); return null; case Load: - code.invokevirtual(p(PyObject.class), "__getitem__", "(" + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__getitem__", sig(PyObject.class, PyObject.class)); return null; case Param: case Store: code.aload(value); - code.invokevirtual(p(PyObject.class), "__setitem__", "(" + $pyObj + $pyObj + ")V"); + code.invokevirtual(p(PyObject.class), "__setitem__", sig(Void.TYPE, PyObject.class, + PyObject.class)); return null; } return null; @@ -1825,15 +1848,16 @@ switch (ctx) { case Del: - code.invokevirtual(p(PyObject.class), "__delattr__", "(" + $str + ")V"); + code.invokevirtual(p(PyObject.class), "__delattr__", sig(Void.TYPE, String.class)); return null; case Load: - code.invokevirtual(p(PyObject.class), "__getattr__", "(" + $str + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__getattr__", sig(PyObject.class, String.class)); return null; case Param: case Store: code.aload(temporary); - code.invokevirtual(p(PyObject.class), "__setattr__", "(" + $str + $pyObj + ")V"); + code.invokevirtual(p(PyObject.class), "__setattr__", sig(Void.TYPE, String.class, + PyObject.class)); return null; } return null; @@ -1910,8 +1934,7 @@ code.ldc("append"); - code.invokevirtual(p(PyObject.class), "__getattr__", "(" + $str + ")" + $pyObj); - + code.invokevirtual(p(PyObject.class), "__getattr__", sig(PyObject.class, String.class)); String tmp_append ="_[" + node.getLine() + "_" + node.getCharPositionInLine() + "]"; set(new Name(node, tmp_append, expr_contextType.Store)); @@ -1961,7 +1984,7 @@ @Override public Object visitRepr(Repr node) throws Exception { visit(node.getInternalValue()); - code.invokevirtual(p(PyObject.class), "__repr__", "()" + $pyStr); + code.invokevirtual(p(PyObject.class), "__repr__", sig(PyString.class)); return null; } @@ -1997,9 +2020,11 @@ false, false, node.getLine(), scope, cflags).get(code); if (!makeClosure(scope)) { - code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class)); + code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, + PyObject[].class, PyCode.class)); } else { - code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class, PyObject[].class)); + code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, + PyObject[].class, PyCode.class, PyObject[].class)); } return null; } @@ -2027,7 +2052,8 @@ code.aload(step); code.freeLocal(step); - code.invokespecial(p(PySlice.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject.class, PyObject.class)); + code.invokespecial(p(PySlice.class), "<init>", sig(Void.TYPE, PyObject.class, + PyObject.class, PyObject.class)); return null; } @@ -2099,7 +2125,7 @@ void emitGetGlobal(String name) throws Exception { code.ldc(name); - code.invokevirtual(p(PyFrame.class), "getglobal", "(" + $str + ")" + $pyObj); + code.invokevirtual(p(PyFrame.class), "getglobal", sig(PyObject.class, String.class)); } @Override @@ -2131,26 +2157,27 @@ if (fast_locals) { if ((flags&ScopeInfo.CELL) != 0) { code.iconst(syminf.env_index); - code.invokevirtual(p(PyFrame.class), "getderef", "(I)" + $pyObj); - + code.invokevirtual(p(PyFrame.class), "getderef", sig(PyObject.class, + Integer.TYPE)); return null; } if ((flags&ScopeInfo.BOUND) != 0) { code.iconst(syminf.locals_index); - code.invokevirtual(p(PyFrame.class), "getlocal", "(I)" + $pyObj); + code.invokevirtual(p(PyFrame.class), "getlocal", sig(PyObject.class, + Integer.TYPE)); return null; } } if ((flags&ScopeInfo.FREE) != 0 && (flags&ScopeInfo.BOUND) == 0) { code.iconst(syminf.env_index); - code.invokevirtual(p(PyFrame.class), "getderef", "(I)" + $pyObj); - + code.invokevirtual(p(PyFrame.class), "getderef", sig(PyObject.class, + Integer.TYPE)); return null; } } code.ldc(name); - code.invokevirtual(p(PyFrame.class), "getname", "(" + $str + ")" + $pyObj); + code.invokevirtual(p(PyFrame.class), "getname", sig(PyObject.class, String.class)); return null; case Param: @@ -2159,12 +2186,14 @@ if (syminf != null && (syminf.flags&ScopeInfo.GLOBAL) != 0) { code.ldc(name); code.aload(temporary); - code.invokevirtual(p(PyFrame.class), "setglobal", "(" + $str + $pyObj + ")V"); + code.invokevirtual(p(PyFrame.class), "setglobal", sig(Void.TYPE, String.class, + PyObject.class)); } else { if (!fast_locals) { code.ldc(name); code.aload(temporary); - code.invokevirtual(p(PyFrame.class), "setlocal", "(" + $str + $pyObj + ")V"); + code.invokevirtual(p(PyFrame.class), "setlocal", sig(Void.TYPE, String.class, + PyObject.class)); } else { if (syminf == null) { throw new ParseException("internal compiler error", node); @@ -2172,11 +2201,13 @@ if ((syminf.flags&ScopeInfo.CELL) != 0) { code.iconst(syminf.env_index); code.aload(temporary); - code.invokevirtual(p(PyFrame.class), "setderef", "(I" + $pyObj + ")V"); + code.invokevirtual(p(PyFrame.class), "setderef", sig(Void.TYPE, + Integer.TYPE, PyObject.class)); } else { code.iconst(syminf.locals_index); code.aload(temporary); - code.invokevirtual(p(PyFrame.class), "setlocal", "(I" + $pyObj + ")V"); + code.invokevirtual(p(PyFrame.class), "setlocal", sig(Void.TYPE, + Integer.TYPE, PyObject.class)); } } } @@ -2185,11 +2216,11 @@ loadFrame(); if (syminf != null && (syminf.flags&ScopeInfo.GLOBAL) != 0) { code.ldc(name); - code.invokevirtual(p(PyFrame.class), "delglobal", "(" + $str + ")V"); + code.invokevirtual(p(PyFrame.class), "delglobal", sig(Void.TYPE, String.class)); } else { if (!fast_locals) { code.ldc(name); - code.invokevirtual(p(PyFrame.class), "dellocal", "(" + $str + ")V"); + code.invokevirtual(p(PyFrame.class), "dellocal", sig(Void.TYPE, String.class)); } else { if (syminf == null) { throw new ParseException("internal compiler error", node); @@ -2199,7 +2230,7 @@ "' referenced in nested scope",true,node); } code.iconst(syminf.locals_index); - code.invokevirtual(p(PyFrame.class), "dellocal", "(I)V"); + code.invokevirtual(p(PyFrame.class), "dellocal", sig(Void.TYPE, Integer.TYPE)); } } return null; } @@ -2264,9 +2295,11 @@ code.aconst_null(); if (!makeClosure(scope)) { - code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class, PyObject.class)); + code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, + PyObject[].class, PyCode.class, PyObject.class)); } else { - code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class, PyObject.class, PyObject[].class)); + code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, + PyObject[].class, PyCode.class, PyObject.class, PyObject[].class)); } int genExp = storeTop(); @@ -2274,10 +2307,10 @@ code.aload(genExp); code.freeLocal(genExp); code.swap(); - code.invokevirtual(p(PyObject.class), "__iter__", "()Lorg/python/core/PyObject;"); + code.invokevirtual(p(PyObject.class), "__iter__", sig(PyObject.class)); loadThreadState(); code.swap(); - code.invokevirtual(p(PyObject.class), "__call__", "(" + $threadState + $pyObj + ")" + $pyObj); + code.invokevirtual(p(PyObject.class), "__call__", sig(PyObject.class, ThreadState.class, PyObject.class)); freeArray(emptyArray); return null; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-10-04 01:16:53
|
Revision: 6830 http://jython.svn.sourceforge.net/jython/?rev=6830&view=rev Author: fwierzbicki Date: 2009-10-04 01:16:45 +0000 (Sun, 04 Oct 2009) Log Message: ----------- Converted invokespecial and getfield to CodegenUtils. 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-03 20:34:59 UTC (rev 6829) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-10-04 01:16:45 UTC (rev 6830) @@ -78,6 +78,7 @@ import org.python.core.ContextManager; import org.python.core.imp; import org.python.core.Py; +import org.python.core.PyCode; import org.python.core.PyComplex; import org.python.core.PyDictionary; import org.python.core.PyException; @@ -219,18 +220,18 @@ private void saveAugTmps(PythonTree node, int count) throws Exception { if (count >= 4) { - augtmp4 = code.getLocal("Lorg/python/core/PyObject;"); + augtmp4 = code.getLocal(ci(PyObject.class)); code.astore(augtmp4); } if (count >= 3) { - augtmp3 = code.getLocal("Lorg/python/core/PyObject;"); + augtmp3 = code.getLocal(ci(PyObject.class)); code.astore(augtmp3); } if (count >= 2) { - augtmp2 = code.getLocal("Lorg/python/core/PyObject;"); + augtmp2 = code.getLocal(ci(PyObject.class)); code.astore(augtmp2); } - augtmp1 = code.getLocal("Lorg/python/core/PyObject;"); + augtmp1 = code.getLocal(ci(PyObject.class)); code.astore(augtmp1); code.aload(augtmp1); @@ -439,9 +440,9 @@ getDocString(node.getInternalBody()); if (!makeClosure(scope)) { - code.invokespecial(p(PyFunction.class), "<init>", "(" + $pyObj + $pyObjArr + $pyCode + $pyObj + ")V"); + code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class, PyObject.class)); } else { - code.invokespecial( p(PyFunction.class), "<init>", "(" + $pyObj + $pyObjArr + $pyCode + $pyObj + $pyObjArr + ")V"); + code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class, PyObject.class, PyObject[].class)); } applyDecorators(node.getInternalDecorator_list()); @@ -1184,7 +1185,7 @@ if (handler.getInternalName() != null) { code.aload(exc); - code.getfield(p(PyException.class), "value", "Lorg/python/core/PyObject;"); + code.getfield(p(PyException.class), "value", ci(PyObject.class)); set(handler.getInternalName()); } @@ -1800,7 +1801,7 @@ code.new_(p(PyTuple.class)); code.dup(); code.aload(dims); - code.invokespecial(p(PyTuple.class), "<init>", "(" + $pyObjArr + ")V"); + code.invokespecial(p(PyTuple.class), "<init>", sig(Void.TYPE, PyObject[].class)); freeArray(dims); return null; } @@ -1878,7 +1879,7 @@ code.dup(); code.aload(content); - code.invokespecial(p(PyTuple.class), "<init>", "(" + $pyObjArr + ")V"); + code.invokespecial(p(PyTuple.class), "<init>", sig(Void.TYPE, PyObject[].class)); freeArray(content); return null; } @@ -1893,7 +1894,7 @@ code.new_(p(PyList.class)); code.dup(); code.aload(content); - code.invokespecial(p(PyList.class), "<init>", "(" + $pyObjArr + ")V"); + code.invokespecial(p(PyList.class), "<init>", sig(Void.TYPE, PyObject[].class)); freeArray(content); return null; } @@ -1903,7 +1904,7 @@ code.new_(p(PyList.class)); code.dup(); - code.invokespecial(p(PyList.class), "<init>", "()V"); + code.invokespecial(p(PyList.class), "<init>", sig(Void.TYPE)); code.dup(); @@ -1952,7 +1953,7 @@ code.new_(p(PyDictionary.class)); code.dup(); code.aload(content); - code.invokespecial(p(PyDictionary.class), "<init>", "(" + $pyObjArr + ")V"); + code.invokespecial(p(PyDictionary.class), "<init>", sig(Void.TYPE, PyObject[].class)); freeArray(content); return null; } @@ -1996,9 +1997,9 @@ false, false, node.getLine(), scope, cflags).get(code); if (!makeClosure(scope)) { - code.invokespecial(p(PyFunction.class), "<init>", "(" + $pyObj + $pyObjArr + $pyCode + ")V"); + code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class)); } else { - code.invokespecial(p(PyFunction.class), "<init>", "(" + $pyObj + $pyObjArr + $pyCode + $pyObjArr + ")V"); + code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class, PyObject[].class)); } return null; } @@ -2006,7 +2007,7 @@ @Override public Object visitEllipsis(Ellipsis node) throws Exception { - code.getstatic(p(Py.class), "Ellipsis", "Lorg/python/core/PyObject;"); + code.getstatic(p(Py.class), "Ellipsis", ci(PyObject.class)); return null; } @@ -2026,7 +2027,7 @@ code.aload(step); code.freeLocal(step); - code.invokespecial(p(PySlice.class), "<init>", "(" + $pyObj + $pyObj + $pyObj + ")V"); + code.invokespecial(p(PySlice.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject.class, PyObject.class)); return null; } @@ -2263,9 +2264,9 @@ code.aconst_null(); if (!makeClosure(scope)) { - code.invokespecial(p(PyFunction.class), "<init>", "(" + $pyObj + $pyObjArr + $pyCode + $pyObj + ")V"); + code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class, PyObject.class)); } else { - code.invokespecial( p(PyFunction.class), "<init>", "(" + $pyObj + $pyObjArr + $pyCode + $pyObj + $pyObjArr + ")V"); + code.invokespecial(p(PyFunction.class), "<init>", sig(Void.TYPE, PyObject.class, PyObject[].class, PyCode.class, PyObject.class, PyObject[].class)); } int genExp = storeTop(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |