KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > python > core > Py


1 // Copyright (c) Corporation for National Research Initiatives
2
package org.python.core;
3
4 import org.python.parser.ast.modType;
5 import java.lang.reflect.InvocationTargetException JavaDoc;
6 import java.io.*;
7
8 public final class Py
9 {
10     static boolean frozen;
11     static String JavaDoc frozenPackage=null;
12     private final static Object JavaDoc PRESENT=new Object JavaDoc();
13     static java.util.Hashtable JavaDoc frozenModules;
14
15     static boolean initialized;
16
17     /* Holds the singleton None and Ellipsis objects */
18     /** The singleton None Python object **/
19     public static PyObject None;
20
21     /** The singleton Ellipsis Python object - written as ... when indexing */
22     public static PyObject Ellipsis;
23
24     /** The singleton NotImplemented Python object. Used in rich comparison */
25     public static PyObject NotImplemented;
26
27     /** A zero-length array of Strings to pass to functions that
28         don't have any keyword arguments **/

29     public static String JavaDoc[] NoKeywords;
30
31     /** A zero-length array of PyObject's to pass to functions that
32         expect zero-arguments **/

33     public static PyObject[] EmptyObjects;
34
35     /** A tuple with zero elements **/
36     public static PyTuple EmptyTuple;
37
38     /** The Python integer 0 - also used as false **/
39     public static PyInteger Zero;
40
41     /** The Python integer 1 - also used as true **/
42     public static PyInteger One;
43
44     /** A zero-length Python string **/
45     public static PyString EmptyString;
46
47     /** A Python string containing '\n' **/
48     public static PyString Newline;
49
50     /** A Python string containing ' ' **/
51     public static PyString Space;
52
53     /** A unique object to indicate no conversion is possible
54         in __tojava__ methods **/

55     public static Object JavaDoc NoConversion;
56
57     public static PyObject OSError;
58     public static PyObject NotImplementedError;
59     public static PyObject EnvironmentError;
60
61
62     /* The standard Python exceptions */
63     public static PyObject OverflowError;
64     public static PyException OverflowError(String JavaDoc message) {
65         return new PyException(Py.OverflowError, message);
66     }
67
68     public static PyObject RuntimeError;
69     public static PyException RuntimeError(String JavaDoc message) {
70         return new PyException(Py.RuntimeError, message);
71     }
72
73     public static PyObject KeyboardInterrupt;
74     /*public static PyException KeyboardInterrupt(String message) {
75       return new PyException(Py.KeyboardInterrupt, message);
76       }*/

77
78     public static PyObject FloatingPointError;
79     public static PyException FloatingPointError(String JavaDoc message) {
80         return new PyException(Py.FloatingPointError, message);
81     }
82
83     public static PyObject SyntaxError;
84     public static PyException SyntaxError(String JavaDoc message) {
85         return new PyException(Py.SyntaxError, message);
86     }
87
88     public static PyObject IndentationError;
89     public static PyObject TabError;
90
91     public static PyObject AttributeError;
92     public static PyException AttributeError(String JavaDoc message) {
93         return new PyException(Py.AttributeError, message);
94     }
95
96     public static PyObject IOError;
97     public static PyException IOError(java.io.IOException JavaDoc ioe) {
98         //System.err.println("ioe: "+ioe);
99
//ioe.printStackTrace();
100
String JavaDoc message = ioe.getMessage();
101         if (ioe instanceof java.io.FileNotFoundException JavaDoc) {
102             message = "File not found - "+message;
103         }
104         return new PyException(Py.IOError, message);
105     }
106     public static PyException IOError(String JavaDoc message) {
107         //System.err.println("sioe: "+message);
108
return new PyException(Py.IOError, message);
109     }
110
111     public static PyObject KeyError;
112     public static PyException KeyError(String JavaDoc message) {
113         return new PyException(Py.KeyError, message);
114     }
115
116     public static PyObject AssertionError;
117     public static PyException AssertionError(String JavaDoc message) {
118         return new PyException(Py.AssertionError, message);
119     }
120
121     public static PyObject TypeError;
122     public static PyException TypeError(String JavaDoc message) {
123         return new PyException(Py.TypeError, message);
124     }
125
126     public static PyObject ReferenceError;
127     public static PyException ReferenceError(String JavaDoc message) {
128         return new PyException(Py.ReferenceError, message);
129     }
130
131     public static PyObject SystemError;
132     public static PyException SystemError(String JavaDoc message) {
133         return new PyException(Py.SystemError, message);
134     }
135
136     public static PyObject IndexError;
137     public static PyException IndexError(String JavaDoc message) {
138         return new PyException(Py.IndexError, message);
139     }
140
141     public static PyObject ZeroDivisionError;
142     public static PyException ZeroDivisionError(String JavaDoc message) {
143         return new PyException(Py.ZeroDivisionError, message);
144     }
145
146     public static PyObject NameError;
147     public static PyException NameError(String JavaDoc message) {
148         return new PyException(Py.NameError, message);
149     }
150
151     public static PyObject UnboundLocalError;
152     public static PyException UnboundLocalError(String JavaDoc message) {
153         return new PyException(Py.UnboundLocalError, message);
154     }
155
156     public static PyObject SystemExit;
157     /*public static PyException SystemExit(String message) {
158       return new PyException(Py.SystemExit, message);
159       }*/

160     static void maybeSystemExit(PyException exc) {
161         //System.err.println("maybeSystemExit: " + exc.type.toString());
162
if (Py.matchException(exc, Py.SystemExit)) {
163             PyObject value = exc.value;
164             //System.err.println("exiting: "+value.getClass().getName());
165
if (value instanceof PyInstance) {
166                 PyObject tmp = value.__findattr__("code");
167                 if (tmp != null)
168                     value = tmp;
169             }
170             Py.getSystemState().callExitFunc();
171             if (value instanceof PyInteger) {
172                 System.exit(((PyInteger)value).getValue());
173             } else {
174                 if (value != Py.None) {
175                     try {
176                         Py.println(value);
177                         System.exit(1);
178                     }
179                     catch (Throwable JavaDoc t0) { }
180                 }
181                 System.exit(0);
182             }
183         }
184     }
185
186     public static PyObject StopIteration;
187     public static PyException StopIteration(String JavaDoc message) {
188         return new PyException(Py.StopIteration, message);
189     }
190
191     public static PyObject ImportError;
192     public static PyException ImportError(String JavaDoc message) {
193         return new PyException(Py.ImportError, message);
194     }
195
196     public static PyObject ValueError;
197     public static PyException ValueError(String JavaDoc message) {
198         return new PyException(Py.ValueError, message);
199     }
200
201     public static PyObject UnicodeError;
202     public static PyException UnicodeError(String JavaDoc message) {
203         return new PyException(Py.UnicodeError, message);
204     }
205
206     public static PyObject EOFError;
207     public static PyException EOFError(String JavaDoc message) {
208         return new PyException(Py.EOFError, message);
209     }
210
211     public static PyObject MemoryError;
212     
213     public static void memory_error(OutOfMemoryError JavaDoc t) {
214         if (Options.showJavaExceptions) {
215             t.printStackTrace();
216         }
217 // this logic would allow to re-enable the old behavior when it makes sense,
218
// or better offer a hook?
219
// try {
220
// byte[] alloc = new byte[(512*1024)];
221
// } catch(OutOfMemoryError oome) {
222
// System.err.println("Out Of Memory");
223
// System.err.println("You might want to try the -mx flag to increase heap size.");
224
// System.exit(-1);
225
// }
226
}
227
228     public static PyException MemoryError(String JavaDoc message) {
229         return new PyException(Py.MemoryError, message);
230     }
231
232     public static PyObject ArithmeticError;
233     public static PyObject LookupError;
234     public static PyObject StandardError;
235     public static PyObject Exception;
236
237     public static PyObject Warning;
238     public static void Warning(String JavaDoc message) {
239         warning(Warning, message);
240     }
241
242     public static PyObject UserWarning;
243     public static void UserWarning(String JavaDoc message) {
244         warning(UserWarning, message);
245     }
246
247     public static PyObject DeprecationWarning;
248     public static void DeprecationWarning(String JavaDoc message) {
249         warning(DeprecationWarning, message);
250     }
251
252     public static PyObject SyntaxWarning;
253     public static void SyntaxWarning(String JavaDoc message) {
254         warning(SyntaxWarning, message);
255     }
256
257     public static PyObject OverflowWarning;
258     public static void OverflowWarning(String JavaDoc message) {
259         warning(OverflowWarning, message);
260     }
261
262     public static PyObject RuntimeWarning;
263     public static void RuntimeWarning(String JavaDoc message) {
264         warning(RuntimeWarning, message);
265     }
266
267     private static PyObject warnings_mod;
268     private static PyObject importWarnings() {
269         if (warnings_mod != null) return warnings_mod;
270         PyObject mod;
271         try {
272             mod = __builtin__.__import__("warnings");
273         } catch(PyException e) {
274             if (matchException(e,ImportError)) {
275                 return null;
276             }
277             throw e;
278         }
279         warnings_mod = mod;
280         return mod;
281     }
282
283     private static String JavaDoc warn_hcategory(PyObject category) {
284         PyObject name = category.__findattr__("__name__");
285         if (name != null) return "["+name+"]";
286         return "[warning]";
287     }
288
289     public static void warning(PyObject category, String JavaDoc message) {
290         PyObject func = null;
291         PyObject mod = importWarnings();
292         if (mod != null)
293             func = mod.__getattr__("warn");
294         if (func == null) {
295             System.err.println(warn_hcategory(category) + ": " + message);
296             return;
297         } else {
298             func.__call__(Py.newString(message), category);
299         }
300     }
301
302     public static void warning(PyObject category, String JavaDoc message,
303                                String JavaDoc filename, int lineno, String JavaDoc module,
304                                PyObject registry)
305     {
306         PyObject func = null;
307         PyObject mod = importWarnings();
308         if (mod != null)
309             func = mod.__getattr__("warn_explicit");
310         if (func == null) {
311             System.err.println(filename + ":" + lineno + ":" +
312                                warn_hcategory(category) + ": " + message);
313             return;
314         } else {
315             func.__call__(new PyObject[] {
316                 Py.newString(message), category,
317                 Py.newString(filename), Py.newInteger(lineno),
318                 (module == null) ? Py.None : Py.newString(module),
319                 registry}, Py.NoKeywords);
320         }
321     }
322
323
324     public static PyObject JavaError;
325     public static PyException JavaError(Throwable JavaDoc t) {
326 // System.err.println("t: "+t);
327
if (t instanceof PyException) {
328             return (PyException)t;
329         }
330         else if (t instanceof InvocationTargetException JavaDoc) {
331             return JavaError(
332                 ((InvocationTargetException JavaDoc)t).getTargetException());
333         }
334 // Remove this automatic coercion, people want to see the real
335
// exceptions!
336
// else if (t instanceof java.io.IOException) {
337
// return IOError((java.io.IOException)t);
338
// }
339
// see corresponding logic in matchException
340
else if (t instanceof OutOfMemoryError JavaDoc) {
341             memory_error((OutOfMemoryError JavaDoc)t);
342         }
343         PyJavaInstance exc = (PyJavaInstance)Py.java2py(t);
344         return new PyException(exc.instclass, exc);
345
346     }
347
348     // Don't allow any constructors. Class only provides static methods.
349
private Py() { ; }
350
351     /** @deprecated **/
352     //public static InterpreterState interp;
353

354     /**
355        Convert a given <code>PyObject</code> to an instance of a Java class.
356        Identical to <code>o.__tojava__(c)</code> except that it will
357        raise a <code>TypeError</code> if the conversion fails.
358
359        @param o the <code>PyObject</code> to convert.
360        @param c the class to convert it to.
361     **/

362     public static Object JavaDoc tojava(PyObject o, Class JavaDoc c) {
363         Object JavaDoc obj = o.__tojava__(c);
364         if (obj == Py.NoConversion) {
365             throw Py.TypeError("can't convert "+o.__repr__()+" to "+
366                                c.getName());
367         }
368         return obj;
369     }
370
371     // ??pending: was @deprecated but is actually used by proxie code.
372
// Can get rid of it?
373
public static Object JavaDoc tojava(PyObject o, String JavaDoc s) {
374         Class JavaDoc c = findClass(s);
375         if (c == null) throw Py.TypeError("can't convert to: "+s);
376         return tojava(o, c); // prev:Class.forName
377
}
378
379     /* Helper functions for PyProxy's */
380
381     /** @deprecated **/
382     public static PyObject jfindattr(PyProxy proxy, String JavaDoc name) {
383         PyInstance o = proxy._getPyInstance();
384         if (o == null) {
385             proxy.__initProxy__(new Object JavaDoc[0]);
386             o = proxy._getPyInstance();
387         }
388         PyObject ret = o.__jfindattr__(name);
389         if (ret == null)
390             return null;
391
392         // Set the current system state to match proxy -- usually
393
// this is a waste of time :-(
394
Py.setSystemState(proxy._getPySystemState());
395         return ret;
396     }
397     /** @deprecated **/
398     public static PyObject jgetattr(PyProxy proxy, String JavaDoc name) {
399         PyInstance o = proxy._getPyInstance();
400         PyObject ret = null;
401         if (o != null) {
402             ret = o.__jfindattr__(name);
403         }
404         if (ret == null)
405             throw Py.AttributeError("abstract method \""+name+
406                                     "\" not implemented");
407         // Set the current system state to match proxy -- usually this is a
408
// waste of time :-(
409
Py.setSystemState(proxy._getPySystemState());
410         return ret;
411     }
412
413     /* Convenience methods to create new constants without using "new" */
414     private static PyInteger[] integerCache = null;
415
416     public static final PyInteger newInteger(int i) {
417         if (integerCache == null) {
418             integerCache = new PyInteger[1000];
419             for(int j=-100; j<900; j++) {
420                 integerCache[j+100] = new PyInteger(j);
421             }
422         }
423         if (i>=-100 && i < 900) {
424             return integerCache[i+100];
425         } else {
426             return new PyInteger(i);
427         }
428     }
429
430     public static PyObject newInteger(long i) {
431         if (i < Integer.MIN_VALUE || i > Integer.MAX_VALUE)
432             return new PyLong(i);
433         else
434             return newInteger((int)i);
435     }
436
437     public static PyLong newLong(String JavaDoc s) {
438         return new PyLong(s);
439     }
440
441     public static PyLong newLong(java.math.BigInteger JavaDoc i) {
442         return new PyLong(i);
443     }
444
445     public static PyComplex newImaginary(double v) {
446         return new PyComplex(0, v);
447     }
448
449     public static PyFloat newFloat(float v) {
450         return new PyFloat((double)v);
451     }
452
453     public static PyFloat newFloat(double v) {
454         return new PyFloat(v);
455     }
456
457     public static PyString newString(char c) {
458         return makeCharacter(c);
459     }
460
461     public static PyString newString(String JavaDoc s) {
462         return new PyString(s);
463     }
464
465     public static PyInteger newBoolean(boolean t) {
466         return t ? Py.One : Py.Zero;
467     }
468
469     // nested scopes:
470
// String[] cellvars,String[] freevars,int npurecell & int moreflags
471

472     public static PyCode newCode(int argcount, String JavaDoc varnames[],
473                                  String JavaDoc filename, String JavaDoc name,
474                                  boolean args, boolean keywords,
475                                  PyFunctionTable funcs, int func_id,
476                                  String JavaDoc[] cellvars,String JavaDoc[] freevars,
477                                  int npurecell, int moreflags)
478     {
479         return new PyTableCode(argcount, varnames,
480                                filename, name, 0, args, keywords, funcs,
481                                func_id, cellvars, freevars, npurecell,
482                                moreflags);
483     }
484
485     public static PyCode newCode(int argcount, String JavaDoc varnames[],
486                                  String JavaDoc filename, String JavaDoc name,
487                                  int firstlineno,
488                                  boolean args, boolean keywords,
489                                  PyFunctionTable funcs, int func_id,
490                                  String JavaDoc[] cellvars,String JavaDoc[] freevars,
491                                  int npurecell, int moreflags)
492
493     {
494         return new PyTableCode(argcount, varnames,
495                                filename, name, firstlineno, args, keywords,
496                                funcs, func_id, cellvars, freevars, npurecell,
497                                moreflags);
498     }
499
500     // --
501

502     public static PyCode newCode(int argcount, String JavaDoc varnames[],
503                                  String JavaDoc filename, String JavaDoc name,
504                                  boolean args, boolean keywords,
505                                  PyFunctionTable funcs, int func_id)
506     {
507         return new PyTableCode(argcount, varnames,
508                                filename, name, 0, args, keywords, funcs,
509                                func_id);
510     }
511
512     public static PyCode newCode(int argcount, String JavaDoc varnames[],
513                                  String JavaDoc filename, String JavaDoc name,
514                                  int firstlineno,
515                                  boolean args, boolean keywords,
516                                  PyFunctionTable funcs, int func_id)
517     {
518         return new PyTableCode(argcount, varnames,
519                                filename, name, firstlineno, args, keywords,
520                                funcs, func_id);
521     }
522
523     public static PyCode newJavaCode(Class JavaDoc cls, String JavaDoc name) {
524         return new JavaCode(newJavaFunc(cls, name));
525     }
526
527     public static PyObject newJavaFunc(Class JavaDoc cls, String JavaDoc name) {
528         try {
529             java.lang.reflect.Method JavaDoc m = cls.getMethod(name, new Class JavaDoc[] {
530                        PyObject[].class, String JavaDoc[].class });
531             return new JavaFunc(m);
532         } catch (NoSuchMethodException JavaDoc e) {
533             throw Py.JavaError(e);
534         }
535     }
536
537     private static PyObject initExc(String JavaDoc name, PyObject exceptions,
538                                     PyObject dict) {
539         PyObject tmp = exceptions.__getattr__(name);
540         dict.__setitem__(name, tmp);
541         return tmp;
542     }
543
544     static void initClassExceptions(PyObject dict) {
545         PyObject exc = imp.load("exceptions");
546
547         Exception = initExc("Exception", exc, dict);
548         SystemExit = initExc("SystemExit", exc, dict);
549         StopIteration = initExc("StopIteration", exc, dict);
550         StandardError = initExc("StandardError", exc, dict);
551         KeyboardInterrupt = initExc("KeyboardInterrupt", exc, dict);
552         ImportError = initExc("ImportError", exc, dict);
553         EnvironmentError = initExc("EnvironmentError", exc, dict);
554         IOError = initExc("IOError", exc, dict);
555         OSError = initExc("OSError", exc, dict);
556         EOFError = initExc("EOFError", exc, dict);
557         RuntimeError = initExc("RuntimeError", exc, dict);
558         NotImplementedError = initExc("NotImplementedError", exc, dict);
559         NameError = initExc("NameError", exc, dict);
560         UnboundLocalError = initExc("UnboundLocalError", exc, dict);
561         AttributeError = initExc("AttributeError", exc, dict);
562         SyntaxError = initExc("SyntaxError", exc, dict);
563         IndentationError = initExc("IndentationError", exc, dict);
564         TabError = initExc("TabError", exc, dict);
565         TypeError = initExc("TypeError", exc, dict);
566         AssertionError = initExc("AssertionError", exc, dict);
567         LookupError = initExc("LookupError", exc, dict);
568         IndexError = initExc("IndexError", exc, dict);
569         KeyError = initExc("KeyError", exc, dict);
570         ArithmeticError = initExc("ArithmeticError", exc, dict);
571         OverflowError = initExc("OverflowError", exc, dict);
572         ZeroDivisionError = initExc("ZeroDivisionError", exc, dict);
573         FloatingPointError = initExc("FloatingPointError", exc, dict);
574         ValueError = initExc("ValueError", exc, dict);
575         UnicodeError = initExc("UnicodeError", exc, dict);
576         ReferenceError = initExc("ReferenceError", exc, dict);
577         SystemError = initExc("SystemError", exc, dict);
578         MemoryError = initExc("MemoryError", exc, dict);
579         Warning = initExc("Warning", exc, dict);
580         UserWarning = initExc("UserWarning", exc, dict);
581         DeprecationWarning = initExc("DeprecationWarning", exc, dict);
582         SyntaxWarning = initExc("SyntaxWarning", exc, dict);
583         OverflowWarning = initExc("OverflowWarning", exc, dict);
584         RuntimeWarning = initExc("RuntimeWarning", exc, dict);
585     }
586
587     public static PySystemState defaultSystemState;
588     // This is a hack to get initializations to work in proper order
589
public static synchronized boolean initPython() {
590         PySystemState.initialize();
591         return true;
592     }
593
594
595     public static Class JavaDoc relFindClass(Class JavaDoc home,String JavaDoc name) {
596         try {
597             ClassLoader JavaDoc loader = home.getClassLoader();
598             if (loader != null) return loader.loadClass(name);
599             else return Class.forName(name);
600         } catch (ClassNotFoundException JavaDoc exc) {
601             return null;
602         } catch (Throwable JavaDoc t) {
603             throw Py.JavaError(t);
604         }
605     }
606
607     private static boolean secEnv=false;
608
609     public static Class JavaDoc findClass(String JavaDoc name) {
610         try {
611             ClassLoader JavaDoc classLoader = Py.getSystemState().getClassLoader();
612             if (classLoader != null) return classLoader.loadClass(name);
613
614             if(!secEnv) {
615                 try {
616                     classLoader = imp.getSyspathJavaLoader();
617                 }
618                 catch(SecurityException JavaDoc e) {
619                     secEnv=true;
620                 }
621                 if (classLoader != null) {
622                     return classLoader.loadClass(name);
623                 }
624             }
625
626             return Class.forName(name);
627
628         }
629         catch (ClassNotFoundException JavaDoc e) {
630             // e.printStackTrace();
631
return null;
632         }
633         catch (IllegalArgumentException JavaDoc e) {
634             // e.printStackTrace();
635
return null;
636         }
637         catch (NoClassDefFoundError JavaDoc e) {
638             // e.printStackTrace();
639
return null;
640         }
641     }
642
643
644     public static Class JavaDoc findClassEx(String JavaDoc name, String JavaDoc reason) {
645         try {
646             ClassLoader JavaDoc classLoader = Py.getSystemState().getClassLoader();
647             if (classLoader != null) {
648                 writeDebug("import", "trying " + name + " as " + reason +
649                            " in classLoader");
650                 return classLoader.loadClass(name);
651             }
652
653             if(!secEnv) {
654                 try {
655                     classLoader = imp.getSyspathJavaLoader();
656                 }
657                 catch(SecurityException JavaDoc e) {
658                     secEnv=true;
659                 }
660                 if (classLoader != null) {
661                     writeDebug("import", "trying " + name + " as " + reason +
662                            " in syspath loader");
663                     return classLoader.loadClass(name);
664                 }
665             }
666
667             writeDebug("import", "trying " + name + " as " + reason +
668                        " in Class.forName");
669             return Class.forName(name);
670         }
671         catch (ClassNotFoundException JavaDoc e) {
672             return null;
673         }
674         catch (IllegalArgumentException JavaDoc e) {
675             throw JavaError(e);
676         }
677         catch (LinkageError JavaDoc e) {
678             throw JavaError(e);
679         }
680     }
681
682     private static void setArgv(String JavaDoc arg0, String JavaDoc[] args) {
683         PyObject argv[] = new PyObject[args.length+1];
684         argv[0] = new PyString(arg0);
685         for(int i=1; i<argv.length; i++)
686             argv[i] = new PyString(args[i-1]);
687         Py.getSystemState().argv = new PyList(argv);
688     }
689
690     private static boolean propertiesInitialized = false;
691     private static synchronized void initProperties(String JavaDoc[] args,
692                                                     String JavaDoc[] packages,
693                                                     String JavaDoc[] props,
694                                                     String JavaDoc frozenPackage,
695                                                     String JavaDoc[] modules,
696                                                     ClassLoader JavaDoc classLoader)
697     {
698         if (!propertiesInitialized) {
699             propertiesInitialized = true;
700
701             if (frozenPackage != null) {
702                 Py.frozen = true;
703                 if (frozenPackage.length() > 0)
704                     Py.frozenPackage = frozenPackage;
705             }
706
707             java.util.Properties JavaDoc sprops;
708             try {
709                 sprops = new java.util.Properties JavaDoc(System.getProperties());
710             } catch (Throwable JavaDoc t) {
711                 sprops = new java.util.Properties JavaDoc();
712             }
713
714             if (props != null) {
715                 for (int i=0; i<props.length; i+=2) {
716                     sprops.put(props[i], props[i+1]);
717                 }
718             }
719             //System.err.println("sprops: "+sprops);
720

721             if (args == null)
722                 args = new String JavaDoc[0];
723             PySystemState.initialize(sprops, null, args, classLoader);
724         }
725
726         if (modules != null) {
727             if(frozenModules == null)
728               frozenModules = new java.util.Hashtable JavaDoc();
729
730             // System.err.println("modules: "); // ?? dbg
731
for (int i = 0; i < modules.length; i++) {
732                 String JavaDoc modname = modules[i];
733                 // System.err.print(modname + " "); // ?? dbg
734
frozenModules.put(modname,PRESENT);
735                 // py pkgs are potentially java pkgs too.
736
if (modname.endsWith(".__init__")) {
737                     String JavaDoc jpkg = modname.substring(0,modname.length()-9);
738                     PySystemState.add_package(jpkg);
739                     // System.err.print(":j "); // ?? dbg
740
}
741             }
742             // System.out.println(); // ?? dbg
743
}
744
745         if (packages != null) {
746             for (int i=0; i<packages.length; i+=2) {
747                 PySystemState.add_package(packages[i], packages[i+1]);
748             }
749         }
750     }
751
752     public static void initProxy(PyProxy proxy, String JavaDoc module, String JavaDoc pyclass,
753                                  Object JavaDoc[] args, String JavaDoc[] packages,
754                                  String JavaDoc[] props, boolean frozen)
755     {
756         initProxy(proxy, module, pyclass, args, packages, props, null, null);
757     }
758
759     public static void initProxy(PyProxy proxy, String JavaDoc module, String JavaDoc pyclass,
760                                  Object JavaDoc[] args, String JavaDoc[] packages,
761                                  String JavaDoc[] props,
762                                  String JavaDoc frozenPackage,
763                                  String JavaDoc[] modules)
764     {
765         initProperties(null, packages, props, frozenPackage, modules,
766                     proxy.getClass().getClassLoader());
767
768         if (proxy._getPyInstance() != null)
769             return;
770
771         ThreadState ts = getThreadState();
772         PyInstance instance = ts.getInitializingProxy();
773         if (instance != null) {
774             if (instance.javaProxy != null)
775                 throw Py.TypeError("Proxy instance reused");
776             instance.javaProxy = proxy;
777             proxy._setPyInstance(instance);
778             proxy._setPySystemState(ts.systemState);
779             return;
780         }
781
782         //System.out.println("path: "+sys.path.__str__());
783
PyObject mod;
784         // ??pending: findClass or should avoid sys.path loading?
785
Class JavaDoc modClass = Py.findClass(module+"$_PyInner");
786         if (modClass != null) {
787             //System.err.println("found as class: "+modClass);
788
PyCode code=null;
789             try {
790                 code = ((PyRunnable)modClass.newInstance()).getMain();
791             } catch (Throwable JavaDoc t) {
792                 throw Py.JavaError(t);
793             }
794             mod = imp.createFromCode(module, code);
795         } else {
796             mod = imp.importName(module.intern(), false);
797             //System.err.println("found as mod: "+mod);
798
}
799         PyClass pyc = (PyClass)mod.__getattr__(pyclass.intern());
800
801         instance = new PyInstance(pyc);
802         instance.javaProxy = proxy;
803         proxy._setPyInstance(instance);
804         proxy._setPySystemState(ts.systemState);
805
806         PyObject[] pargs;
807         if (args == null || args.length == 0) {
808             pargs = Py.EmptyObjects;
809         } else {
810             pargs = new PyObject[args.length];
811             for(int i=0; i<args.length; i++)
812                 pargs[i] = Py.java2py(args[i]);
813         }
814         instance.__init__(pargs, Py.NoKeywords);
815     }
816
817     public static void initRunnable(String JavaDoc module, PyObject dict) {
818         Class JavaDoc mainClass=null;
819         try {
820             // ??pending: should use Py.findClass?
821
mainClass = Class.forName(module);
822         } catch (ClassNotFoundException JavaDoc exc) {
823             System.err.println("Error running main. Can't find: "+module);
824             System.exit(-1);
825         }
826         PyCode code=null;
827         try {
828             code = ((PyRunnable)mainClass.newInstance()).getMain();
829         } catch (Throwable JavaDoc t) {
830             System.err.println("Invalid class (runnable): "+module+"$py");
831             System.exit(-1);
832         }
833         Py.runCode(code, dict, dict);
834     }
835
836     public static void runMain(Class JavaDoc mainClass, String JavaDoc[] args,
837                                String JavaDoc[] packages,
838                                String JavaDoc[] props,
839                                String JavaDoc frozenPackage,
840                                String JavaDoc[] modules) throws Exception JavaDoc
841     {
842         //System.err.println("main: "+module);
843

844         initProperties(args, packages, props, frozenPackage, modules,
845                        mainClass.getClassLoader());
846
847         try {
848             PyCode code=null;
849             try {
850                 code = ((PyRunnable)mainClass.newInstance()).getMain();
851             } catch (Throwable JavaDoc t) {
852                 System.err.println("Invalid class: " + mainClass.getName() +
853                                    "$py");
854                 System.exit(-1);
855             }
856             PyObject mod = imp.createFromCode("__main__", code);
857         } catch (PyException e) {
858             Py.getSystemState().callExitFunc();
859             if (Py.matchException(e, Py.SystemExit))
860                 return;
861             throw e;
862         }
863         Py.getSystemState().callExitFunc();
864     }
865
866     private static String JavaDoc getStackTrace(Throwable JavaDoc javaError) {
867         ByteArrayOutputStream buf = new ByteArrayOutputStream();
868         javaError.printStackTrace(new PrintStream(buf));
869
870         String JavaDoc str = buf.toString();
871         int index = -1;
872         if (index == -1)
873             index = str.indexOf(
874                 "at org.python.core.PyReflectedConstructor.call");
875         if (index == -1)
876             index = str.indexOf("at org.python.core.PyReflectedMethod.call");
877         if (index == -1)
878             index = str.indexOf(
879                 "at org/python/core/PyReflectedConstructor.call");
880         if (index == -1)
881             index = str.indexOf("at org/python/core/PyReflectedMethod.call");
882
883         if (index != -1)
884             index = str.lastIndexOf("\n", index);
885
886         int index0 = str.indexOf("\n");
887
888         if (index >= index0)
889             str = str.substring(index0+1,index+1);
890
891         return str;
892     }
893
894     /* Display a PyException and stack trace */
895     public static void printException(Throwable JavaDoc t) {
896         printException(t, null, null);
897     }
898
899     public static void printException(Throwable JavaDoc t, PyFrame f) {
900         printException(t, f, null);
901     }
902
903     public static synchronized void printException(Throwable JavaDoc t, PyFrame f,
904                                                    PyObject file)
905     {
906         //System.err.println("printingException: "+t+", "+file);
907
StdoutWrapper stderr = Py.stderr;
908
909         if (file != null) {
910             stderr = new FixedFileWrapper(file);
911         }
912
913         if (Options.showJavaExceptions) {
914             stderr.println("Java Traceback:");
915             java.io.CharArrayWriter JavaDoc buf = new java.io.CharArrayWriter JavaDoc();
916             if (t instanceof PyException) {
917                 ((PyException)t).super__printStackTrace(
918                     new java.io.PrintWriter JavaDoc(buf));
919             } else {
920                 t.printStackTrace(new java.io.PrintWriter JavaDoc(buf));
921             }
922             stderr.print(buf.toString());
923         }
924
925         PyException exc = Py.JavaError(t);
926
927         maybeSystemExit(exc);
928
929         setException(exc, f);
930
931         ThreadState ts = getThreadState();
932
933         ts.systemState.last_value = exc.value;
934         ts.systemState.last_type = exc.type;
935         ts.systemState.last_traceback = exc.traceback;
936
937         PyObject exceptHook = ts.systemState.__findattr__("excepthook");
938         if (exceptHook != null) {
939             try {
940                 exceptHook.__call__(exc.type, exc.value, exc.traceback);
941             } catch (PyException exc2) {
942                 stderr.println("Error in sys.excepthook:");
943                 displayException(exc2.type, exc2.value, exc2.traceback, file);
944                 stderr.println();
945                 stderr.println("Original exception was:");
946                 displayException(exc.type, exc.value, exc.traceback, file);
947             }
948         } else {
949             stderr.println("sys.excepthook is missing");
950             displayException(exc.type, exc.value, exc.traceback, file);
951         }
952
953         ts.exception = null;
954     }
955
956     public static void displayException(PyObject type, PyObject value,
957                                         PyObject tb, PyObject file)
958     {
959         StdoutWrapper stderr = Py.stderr;
960         if (file != null) {
961             stderr = new FixedFileWrapper(file);
962         }
963
964         if (tb instanceof PyTraceback)
965             stderr.print(((PyTraceback) tb).dumpStack());
966         if (__builtin__.isinstance(value, (PyClass) Py.SyntaxError)) {
967             stderr.println(" File \""+value.__findattr__("filename")+
968                            "\", line "+value.__findattr__("lineno"));
969             PyObject text = value.__findattr__("text");
970             if (text != Py.None && text.__len__() != 0) {
971                 stderr.println("\t"+text);
972                 String JavaDoc space = "\t";
973                 int col = ((PyInteger)value.__findattr__("offset").__int__()).getValue();
974                 for(int j=1; j<col; j++)
975                     space = space+" ";
976                 stderr.println(space+"^");
977             }
978         }
979
980         if (value instanceof PyJavaInstance) {
981             Object JavaDoc javaError = value.__tojava__(Throwable JavaDoc.class);
982
983             if (javaError != null && javaError != Py.NoConversion) {
984                 stderr.println(getStackTrace((Throwable JavaDoc)javaError));
985             }
986         }
987         stderr.println(formatException(type, value, tb));
988     }
989
990     static String JavaDoc formatException(PyObject type, PyObject value, PyObject tb) {
991         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
992
993         PyObject typeName;
994         if (type instanceof PyClass) {
995             buf.append(((PyClass) type).__name__);
996         } else {
997             buf.append(type.__str__());
998         }
999         if (value != Py.None) {
1000            buf.append(": ");
1001            if (__builtin__.isinstance(value, (PyClass) Py.SyntaxError)) {
1002                buf.append(value.__getitem__(0).__str__());
1003            } else {
1004                buf.append(value.__str__());
1005            }
1006        }
1007        return buf.toString();
1008    }
1009
1010
1011    /* Equivalent to Python's assert statement */
1012    public static void assert_(PyObject test, PyObject message) {
1013        if (!test.__nonzero__()) {
1014            throw new PyException(Py.AssertionError, message);
1015        }
1016    }
1017
1018    public static void assert_(PyObject test) {
1019        assert_(test, Py.None);
1020    }
1021
1022    /* Helpers to implement finally clauses */
1023    public static void addTraceback(Throwable JavaDoc t, PyFrame frame) {
1024        PyException e = Py.JavaError(t);
1025
1026        //Add another traceback object to the exception if needed
1027
if (e.traceback.tb_frame != frame) {
1028            e.traceback = new PyTraceback(e.traceback);
1029        }
1030    }
1031
1032    /* Helpers to implement except clauses */
1033    public static PyException setException(Throwable JavaDoc t, PyFrame frame) {
1034        //System.out.println("Py.setException");
1035
PyException pye = Py.JavaError(t);
1036        pye.instantiate();
1037
1038        // attach catching frame
1039
if (frame != null && pye.traceback.tb_frame != frame) {
1040            pye.traceback = new PyTraceback(pye.traceback);
1041        }
1042       
1043        ThreadState ts = getThreadState();
1044
1045        ts.exception = pye;
1046
1047        return pye;
1048    }
1049
1050    public static boolean matchException(PyException pye, PyObject e) {
1051        pye.instantiate();
1052        // FIXME, see bug 737978
1053
//
1054
// A special case for IOError's to allow them to also match
1055
// java.io.IOExceptions. This is a hack for 1.0.x until I can do
1056
// it right in 1.1
1057
if (e == Py.IOError) {
1058            if (__builtin__.isinstance(
1059                pye.value,
1060                PyJavaClass.lookup(java.io.IOException JavaDoc.class)))
1061            {
1062                return true;
1063            }
1064        }
1065        // FIXME too, same approach for OutOfMemoryError
1066
if (e == Py.MemoryError) {
1067            if (__builtin__.isinstance(
1068                pye.value,
1069                PyJavaClass.lookup(java.lang.OutOfMemoryError JavaDoc.class)))
1070            {
1071                return true;
1072            }
1073        }
1074        if (e == Py.IOError) {
1075            if (__builtin__.isinstance(
1076                pye.value,
1077                PyJavaClass.lookup(java.io.IOException JavaDoc.class)))
1078            {
1079                return true;
1080            }
1081        }
1082        // same approach for OutOfMemoryError
1083

1084        if (e instanceof PyClass) {
1085            return __builtin__.isinstance(pye.value, (PyClass)e);
1086        }
1087        else {
1088            if (e == pye.type)
1089                return true;
1090
1091            if (e instanceof PyTuple) {
1092                PyObject[] l = ((PyTuple)e).getArray();
1093                for (int i=0; i<l.length; i++) {
1094                    if (matchException(pye, l[i]))
1095                        return true;
1096                }
1097            }
1098            return false;
1099        }
1100    }
1101
1102    /* Implement the raise statement */
1103    // reraise the current exception
1104
public static PyException makeException() {
1105        ThreadState ts = getThreadState();
1106        if (ts.exception == null) {
1107            throw Py.ValueError("no exception to reraise");
1108        }
1109        return ts.exception;
1110    }
1111
1112    public static PyException makeException(PyObject type) {
1113        if (type instanceof PyInstance) {
1114            return new PyException(type.fastGetClass(), type);
1115        } else {
1116            return makeException(type, Py.None);
1117        }
1118    }
1119
1120    public static PyException makeException(PyObject type, PyObject value) {
1121        if (type instanceof PyInstance) {
1122            if (value != Py.None) {
1123                throw TypeError("instance exceptions may not have " +
1124                                "a separate value");
1125            } else {
1126                return new PyException(type.fastGetClass(), type);
1127            }
1128        }
1129        PyException exc = new PyException(type, value);
1130        exc.instantiate();
1131        return exc;
1132    }
1133
1134    public static PyException makeException(PyObject type, PyObject value,
1135                                            PyObject traceback)
1136    {
1137        if (type instanceof PyInstance) {
1138            if (value != Py.None) {
1139                throw TypeError("instance exceptions may not have " +
1140                                "a separate value");
1141            } else {
1142                type = type.fastGetClass();
1143                //return new PyException(type.__class__, type);
1144
}
1145        }
1146
1147        if (traceback == None)
1148            return new PyException(type, value);
1149        if (!(traceback instanceof PyTraceback))
1150            throw TypeError("raise 3rd arg must be traceback or None");
1151
1152        return new PyException(type, value, (PyTraceback)traceback);
1153    }
1154
1155
1156    public static PyObject runCode(PyCode code, PyObject locals,
1157                                   PyObject globals)
1158    {
1159        //System.out.println("run code");
1160
PyFrame f;
1161        /*if (globals == null && locals == null) {
1162          f = Py.getFrame();
1163          } else {*/

1164        if (locals == null) {
1165            if (globals != null) {
1166                locals = globals;
1167            } else {
1168                locals = Py.getFrame().getf_locals();
1169            }
1170        }
1171
1172        if (globals == null)
1173            globals = Py.getFrame().f_globals;
1174
1175        PyTableCode tc=null;
1176        if (code instanceof PyTableCode)
1177            tc = (PyTableCode)code;
1178
1179        f = new PyFrame(tc, locals, globals,
1180                        Py.getThreadState().systemState.builtins);
1181        //}
1182
return code.call(f);
1183    }
1184
1185    public static void exec(PyObject o, PyObject globals, PyObject locals) {
1186        PyCode code;
1187        if (o instanceof PyCode)
1188            code = (PyCode)o;
1189        else {
1190            String JavaDoc contents = null;
1191            if (o instanceof PyString)
1192                contents = o.toString();
1193            else if (o instanceof PyFile) {
1194                PyFile fp = (PyFile)o;
1195                if (fp.closed)
1196                    return;
1197                contents = fp.read().toString();
1198            } else
1199                throw Py.TypeError(
1200                    "exec: argument 1 must be string, code or file object");
1201            code = Py.compile_flags(contents, "<string>", "exec",
1202                                    Py.getCompilerFlags());
1203        }
1204        Py.runCode(code, locals, globals);
1205    }
1206
1207    private static ThreadStateMapping threadStateMapping = null;
1208
1209    public static final ThreadState getThreadState() {
1210        return getThreadState(null);
1211    }
1212
1213    public static final ThreadState
1214        getThreadState(PySystemState newSystemState)
1215    {
1216        if (threadStateMapping == null) {
1217            synchronized (Py.class) {
1218                if (threadStateMapping == null)
1219                    threadStateMapping = ThreadStateMapping.makeMapping();
1220            }
1221        }
1222        return threadStateMapping.getThreadState(newSystemState);
1223    }
1224
1225    public static final PySystemState
1226        setSystemState(PySystemState newSystemState)
1227    {
1228        ThreadState ts = getThreadState(newSystemState);
1229        PySystemState oldSystemState = ts.systemState;
1230        if (oldSystemState != newSystemState) {
1231            //System.err.println("Warning: changing systemState "+
1232
// "for same thread!");
1233
ts.systemState = newSystemState;
1234        }
1235        return oldSystemState;
1236    }
1237
1238    public static final PySystemState getSystemState() {
1239        return getThreadState().systemState;
1240        //defaultSystemState;
1241
}
1242
1243    /* Get and set the current frame */
1244
1245    public static PyFrame getFrame() {
1246        //System.out.println("getFrame");
1247
ThreadState ts = getThreadState();
1248        if (ts == null)
1249            return null;
1250        return ts.frame;
1251    }
1252
1253    public static void setFrame(PyFrame f) {
1254        //System.out.println("setFrame");
1255
getThreadState().frame = f;
1256    }
1257
1258    /* These are not used anymore. Uncomment them if there is a future
1259       clamor to make this functionality more easily usable
1260       public static void pushFrame(PyFrame f) {
1261       ThreadState ts = getThreadState();
1262       f.f_back = ts.frame;
1263       if (f.f_builtins == null) f.f_builtins = f.f_back.f_builtins;
1264       ts.frame = f;
1265       }
1266
1267       public static PyFrame popFrame() {
1268       ThreadState ts = getThreadState();
1269       PyFrame f = ts.frame.f_back;
1270       ts.frame = f;
1271       return f;
1272       }
1273    */

1274
1275    /* A collection of functions for implementing the print statement */
1276
1277    public static StdoutWrapper stderr;
1278    static StdoutWrapper stdout;
1279    //public static StdinWrapper stdin;
1280

1281    public static void print(PyObject file, PyObject o) {
1282        if (file == None)
1283            print(o);
1284        else
1285            new FixedFileWrapper(file).print(o);
1286    }
1287    public static void printComma(PyObject file, PyObject o) {
1288        if (file == None)
1289            printComma(o);
1290        else
1291            new FixedFileWrapper(file).printComma(o);
1292    }
1293    public static void println(PyObject file, PyObject o) {
1294        if (file == None)
1295            println(o);
1296        else
1297            new FixedFileWrapper(file).println(o);
1298    }
1299    public static void printlnv(PyObject file) {
1300        if (file == None)
1301            println();
1302        else
1303            new FixedFileWrapper(file).println();
1304    }
1305
1306    public static void print(PyObject o) {
1307        stdout.print(o);
1308    }
1309    public static void printComma(PyObject o) {
1310        stdout.printComma(o);
1311    }
1312    public static void println(PyObject o) {
1313        stdout.println(o);
1314    }
1315    public static void println() {
1316        stdout.println();
1317    }
1318
1319    /* A collection of convenience functions for converting PyObjects
1320       to Java primitives */

1321
1322    public static boolean py2boolean(PyObject o) {
1323        return o.__nonzero__();
1324    }
1325
1326    public static byte py2byte(PyObject o) {
1327        if (o instanceof PyInteger) return (byte)((PyInteger)o).getValue();
1328
1329        Object JavaDoc i = o.__tojava__(Byte.TYPE);
1330        if (i == null || i == Py.NoConversion)
1331            throw Py.TypeError("integer required");
1332        return ((Byte JavaDoc) i).byteValue();
1333    }
1334    public static short py2short(PyObject o) {
1335        if (o instanceof PyInteger)
1336            return (short)((PyInteger)o).getValue();
1337
1338        Object JavaDoc i = o.__tojava__(Short.TYPE);
1339        if (i == null || i == Py.NoConversion)
1340            throw Py.TypeError("integer required");
1341        return ((Short JavaDoc) i).shortValue();
1342    }
1343
1344    public static int py2int(PyObject o) {
1345        return py2int(o, "integer required");
1346    }
1347
1348    public static int py2int(PyObject o, String JavaDoc msg) {
1349        if (o instanceof PyInteger)
1350            return (int)((PyInteger)o).getValue();
1351        Object JavaDoc obj = o.__tojava__(Integer.TYPE);
1352        if (obj == Py.NoConversion)
1353            throw Py.TypeError(msg);
1354        return ((Integer JavaDoc)obj).intValue();
1355    }
1356
1357    public static long py2long(PyObject o) {
1358        if (o instanceof PyInteger)
1359            return (long)((PyInteger)o).getValue();
1360
1361        Object JavaDoc i = o.__tojava__(Long.TYPE);
1362        if (i == null || i == Py.NoConversion)
1363            throw Py.TypeError("integer required");
1364        return ((Long JavaDoc) i).longValue();
1365    }
1366
1367    public static float py2float(PyObject o) {
1368        if (o instanceof PyFloat)
1369            return (float)((PyFloat)o).getValue();
1370        if (o instanceof PyInteger)
1371            return (float)((PyInteger)o).getValue();
1372
1373        Object JavaDoc i = o.__tojava__(Float.TYPE);
1374        if (i == null || i == Py.NoConversion)
1375            throw Py.TypeError("float required");
1376        return ((Float JavaDoc) i).floatValue();
1377    }
1378    public static double py2double(PyObject o) {
1379        if (o instanceof PyFloat)
1380            return (double)((PyFloat)o).getValue();
1381        if (o instanceof PyInteger)
1382            return (double)((PyInteger)o).getValue();
1383
1384        Object JavaDoc i = o.__tojava__(Double.TYPE);
1385        if (i == null || i == Py.NoConversion)
1386            throw Py.TypeError("float required");
1387        return ((Double JavaDoc) i).doubleValue();
1388    }
1389
1390    public static char py2char(PyObject o) {
1391        return py2char(o, "char required");
1392    }
1393
1394    public static char py2char(PyObject o, String JavaDoc msg) {
1395        if (o instanceof PyString) {
1396            PyString s = (PyString)o;
1397            if (s.__len__() != 1)
1398                throw Py.TypeError(msg);
1399            return s.toString().charAt(0);
1400        }
1401        if (o instanceof PyInteger) {
1402            return (char)((PyInteger)o).getValue();
1403        }
1404
1405        Object JavaDoc i = o.__tojava__(Character.TYPE);
1406        if (i == null || i == Py.NoConversion)
1407            throw Py.TypeError(msg);
1408        return ((Character JavaDoc) i).charValue();
1409    }
1410
1411    public static void py2void(PyObject o) {
1412        if (o != Py.None) {
1413            throw Py.TypeError("None required for void return");
1414        }
1415    }
1416
1417    private static PyString[] letters=null;
1418
1419
1420    static final PyString makeCharacter(Character JavaDoc o) {
1421        return makeCharacter(o.charValue());
1422    }
1423
1424    static final PyString makeCharacter(char c) {
1425        if (c > 255) {
1426            return new PyString(new Character JavaDoc(c).toString());
1427        }
1428
1429        if (letters == null) {
1430            letters = new PyString[256];
1431            for(char j=0; j<256; j++) {
1432                letters[j] = new PyString(new Character JavaDoc(j).toString());
1433            }
1434        }
1435        return letters[c];
1436    }
1437
1438    // Needs rewriting for efficiency and extensibility
1439
public static PyObject java2py(Object JavaDoc o) {
1440        if (o instanceof PyObject)
1441            return (PyObject)o;
1442
1443        if (o instanceof PyProxy)
1444            return ((PyProxy)o)._getPyInstance();
1445
1446        if (o instanceof Number JavaDoc) {
1447            if (o instanceof Double JavaDoc || o instanceof Float JavaDoc) {
1448                return new PyFloat(((Number JavaDoc)o).doubleValue());
1449            }
1450            else if (o instanceof Long JavaDoc) {
1451                return new PyLong(((Number JavaDoc)o).longValue());
1452            }
1453            else if (o instanceof Integer JavaDoc ||
1454                     o instanceof Byte JavaDoc ||
1455                     o instanceof Short JavaDoc)
1456            {
1457                return new PyInteger(((Number JavaDoc)o).intValue());
1458            }
1459        }
1460        if (o instanceof Boolean JavaDoc) {
1461            return ((Boolean JavaDoc)o).booleanValue() ? Py.One : Py.Zero;
1462        }
1463        if (o == null) return Py.None;
1464        if (o instanceof String JavaDoc) return new PyString((String JavaDoc)o);
1465        if (o instanceof Character JavaDoc) return makeCharacter((Character JavaDoc)o);
1466        if (o instanceof Class JavaDoc) {
1467            Class JavaDoc cls = (Class JavaDoc)o;
1468            if (PyObject.class.isAssignableFrom(cls)) {
1469                return PyType.fromClass(cls);
1470            }
1471            return PyJavaClass.lookup(cls);
1472        }
1473
1474        Class JavaDoc c = o.getClass();
1475        if (c.isArray()) {
1476            return new PyArray(c.getComponentType(), o);
1477        }
1478        return new PyJavaInstance(o);
1479    }
1480
1481    public static PyObject makeClass(String JavaDoc name, PyObject[] bases,
1482                                     PyCode code, PyObject doc)
1483    {
1484        return makeClass(name, bases, code, doc, null, null);
1485    }
1486
1487    public static PyObject makeClass(String JavaDoc name, PyObject[] bases,
1488                                     PyCode code, PyObject doc,
1489                                     PyObject[] closure_cells)
1490    {
1491        return makeClass(name, bases, code, doc, null, closure_cells);
1492    }
1493
1494
1495    public static PyObject makeClass(String JavaDoc name, PyObject[] bases,
1496                                     PyCode code, PyObject doc,
1497                                     Class JavaDoc proxyClass) {
1498        return makeClass(name, bases, code, doc, proxyClass, null);
1499    }
1500
1501
1502    private static Class JavaDoc[] pyClassCtrSignature = {
1503        String JavaDoc.class, PyTuple.class, PyObject.class, Class JavaDoc.class
1504    };
1505
1506    static private final PyType CLASS_TYPE = PyType.fromClass(PyClass.class);
1507    
1508
1509    public static PyObject makeClass(String JavaDoc name, PyObject[] bases,
1510                                     PyCode code, PyObject doc,
1511                                     Class JavaDoc proxyClass,
1512                                     PyObject[] closure_cells)
1513    {
1514        PyFrame frame = getFrame();
1515        PyObject globals = frame.f_globals;
1516
1517        PyObject dict = code.call(Py.EmptyObjects, Py.NoKeywords,
1518                                  globals, Py.EmptyObjects,
1519                                  new PyTuple(closure_cells));
1520        if (doc != null)
1521            dict.__setitem__("__doc__", doc);
1522
1523        PyObject metaclass;
1524        
1525        metaclass = dict.__finditem__("__metaclass__");
1526        
1527        if (metaclass == null) {
1528            if (bases.length != 0) {
1529                PyObject base = bases[0];
1530                
1531                if (base instanceof PyMetaClass) {
1532                    // jython-only, experimental PyMetaClass hook
1533
// xxx keep?
1534
try {
1535                        java.lang.reflect.Constructor JavaDoc ctor =
1536                            base.getClass().getConstructor(pyClassCtrSignature);
1537                        return (PyObject) ctor.newInstance(
1538                            new Object JavaDoc[] {
1539                                name,
1540                                new PyTuple(bases),
1541                                dict,
1542                                proxyClass });
1543                    } catch (Exception JavaDoc e) {
1544                        throw Py.TypeError(
1545                            "meta-class fails to supply proper "
1546                                + "ctr: "
1547                                + base.safeRepr());
1548                    }
1549                }
1550                metaclass = base.__findattr__("__class__");
1551                if (metaclass == null) {
1552                    metaclass = base.getType();
1553                }
1554            } else {
1555                if (globals != null)
1556                    metaclass = globals.__finditem__("__metaclass__");
1557            }
1558        }
1559
1560        if (metaclass == null || metaclass == CLASS_TYPE ||
1561             (metaclass instanceof PyJavaClass && ((PyJavaClass)metaclass).proxyClass == Class JavaDoc.class) ) {
1562            return new PyClass(name, new PyTuple(bases), dict, proxyClass);
1563        }
1564        
1565        if (proxyClass != null) {
1566            throw Py.TypeError("the meta-class cannot handle java subclassing");
1567        }
1568 
1569        return metaclass.__call__(new PyString(name),new PyTuple(bases),dict);
1570    }
1571
1572    private static int nameindex=0;
1573    public static synchronized String JavaDoc getName() {
1574        String JavaDoc name = "org.python.pycode._pyx"+nameindex;
1575        nameindex += 1;
1576        return name;
1577    }
1578
1579    public static CompilerFlags getCompilerFlags() {
1580        return getCompilerFlags(0,false);
1581    }
1582
1583    public static CompilerFlags getCompilerFlags(int flags,boolean dont_inherit) {
1584        CompilerFlags cflags = null;
1585        if (dont_inherit) {
1586            cflags = new CompilerFlags(flags);
1587        } else {
1588            PyFrame frame = Py.getFrame();
1589            if (frame!=null && frame.f_code != null) {
1590                cflags = new CompilerFlags(frame.f_code.co_flags|flags);
1591            }
1592        }
1593        return cflags;
1594    }
1595
1596    // w/o compiler-flags
1597

1598    public static PyCode compile(modType node, String JavaDoc filename) {
1599        return compile(node, getName(), filename);
1600    }
1601
1602    public static PyCode compile(modType node, String JavaDoc name,
1603                                 String JavaDoc filename)
1604    {
1605        return compile(node, name, filename, true, false);
1606    }
1607
1608    public static PyCode compile(modType node, String JavaDoc name,
1609                                 String JavaDoc filename,
1610                                 boolean linenumbers,
1611                                 boolean printResults)
1612    {
1613        return compile_flags(node, name, filename, linenumbers,
1614                             printResults, null);
1615    }
1616
1617    public static PyCode compile(InputStream istream, String JavaDoc filename,
1618                                 String JavaDoc type)
1619    {
1620        return compile_flags(istream,filename,type,null);
1621    }
1622
1623    // with compiler-flags
1624

1625    public static PyCode compile_flags(modType node, String JavaDoc name,
1626                                 String JavaDoc filename,
1627                                 boolean linenumbers,
1628                                 boolean printResults,CompilerFlags cflags)
1629    {
1630        try {
1631            ByteArrayOutputStream ostream = new ByteArrayOutputStream();
1632            org.python.compiler.Module.compile(node, ostream, name, filename,
1633                                               linenumbers, printResults,
1634                                               false,cflags);
1635
1636            saveClassFile(name, ostream);
1637
1638            return BytecodeLoader.makeCode(name, ostream.toByteArray());
1639        } catch (Throwable JavaDoc t) {
1640            throw parser.fixParseError(null, t, filename);
1641        }
1642    }
1643
1644    public static PyCode compile_flags(InputStream istream, String JavaDoc filename,
1645                                 String JavaDoc type,CompilerFlags cflags)
1646    {
1647        modType node = parser.parse(istream, type, filename, cflags);
1648        boolean printResults = false;
1649        if (type.equals("single"))
1650            printResults = true;
1651        return Py.compile_flags(node, getName(), filename, true, printResults,
1652                                cflags);
1653    }
1654
1655    public static PyCode compile_flags(String JavaDoc data, String JavaDoc filename,
1656                                       String JavaDoc type,CompilerFlags cflags)
1657    {
1658        return Py.compile_flags(
1659            new java.io.StringBufferInputStream JavaDoc(data+"\n\n"),
1660                          filename, type,cflags);
1661    }
1662
1663    public static PyObject compile_command_flags(String JavaDoc string,
1664                    String JavaDoc filename, String JavaDoc kind, CompilerFlags cflags,boolean stdprompt)
1665    {
1666        org.python.parser.ast.modType node =
1667            parser.partialParse(string+"\n", kind, filename, cflags, stdprompt);
1668    
1669        if (node == null)
1670            return Py.None;
1671        return Py.compile_flags(node, Py.getName(), filename, true, true,
1672                                cflags);
1673    }
1674    
1675    public static PyObject[] unpackSequence(PyObject o, int length) {
1676        if (o instanceof PyTuple) {
1677            PyTuple tup = (PyTuple)o;
1678            //System.err.println("unpack tuple");
1679
if (tup.__len__() == length)
1680                return tup.getArray();
1681            throw Py.ValueError("unpack tuple of wrong size");
1682        }
1683
1684        PyObject[] ret = new PyObject[length];
1685        PyObject iter = o.__iter__();
1686        try {
1687            for (int i = 0; i < length; i++) {
1688                PyObject tmp = iter.__iternext__();
1689                if (tmp == null) {
1690                    throw Py.ValueError("unpack sequence too short");
1691                }
1692                ret[i] = tmp;
1693            }
1694        } catch (PyException exc) {
1695            if (Py.matchException(exc, Py.AttributeError)) {
1696                throw Py.TypeError("unpack non-sequence");
1697            } else {
1698                throw exc;
1699            }
1700        }
1701
1702        if (iter.__iternext__() != null) {
1703            throw Py.ValueError("unpack sequence too long");
1704        }
1705        return ret;
1706    }
1707
1708    public static PyObject iter(PyObject seq, String JavaDoc message) {
1709        try {
1710            return seq.__iter__();
1711        } catch (PyException exc) {
1712            if (Py.matchException(exc, Py.TypeError))
1713                throw Py.TypeError(message);
1714            throw exc;
1715        }
1716    }
1717
1718    private static IdImpl idimpl = IdImpl.getInstance();
1719
1720    public static long id(PyObject o) {
1721        return idimpl.id(o);
1722    }
1723    
1724    public static String JavaDoc idstr(PyObject o) {
1725        return idimpl.idstr(o);
1726    }
1727    
1728    public static long java_obj_id(Object JavaDoc o) {
1729        return idimpl.java_obj_id(o);
1730    }
1731    
1732    public static String JavaDoc safeRepr(PyObject o) {
1733        return o.safeRepr();
1734    }
1735
1736    public static void printResult(PyObject ret) {
1737        Py.getThreadState().systemState.invoke("displayhook", ret);
1738    }
1739
1740    public static final int ERROR=-1;
1741    public static final int WARNING=0;
1742    public static final int MESSAGE=1;
1743    public static final int COMMENT=2;
1744    public static final int DEBUG=3;
1745
1746    public static void maybeWrite(String JavaDoc type, String JavaDoc msg, int level) {
1747        if (level <= Options.verbose) {
1748            System.err.println(type+": "+msg);
1749        }
1750    }
1751
1752    public static void writeError(String JavaDoc type, String JavaDoc msg) {
1753        maybeWrite(type, msg, ERROR);
1754    }
1755    public static void writeWarning(String JavaDoc type, String JavaDoc msg) {
1756        maybeWrite(type, msg, WARNING);
1757    }
1758    public static void writeMessage(String JavaDoc type, String JavaDoc msg) {
1759        maybeWrite(type, msg, MESSAGE);
1760    }
1761    public static void writeComment(String JavaDoc type, String JavaDoc msg) {
1762        maybeWrite(type, msg, COMMENT);
1763    }
1764    public static void writeDebug(String JavaDoc type, String JavaDoc msg) {
1765        maybeWrite(type, msg, DEBUG);
1766    }
1767
1768
1769    public static void saveClassFile(String JavaDoc name, ByteArrayOutputStream bytestream) {
1770        String JavaDoc dirname = Options.proxyDebugDirectory;
1771        if (dirname == null)
1772            return;
1773
1774        byte[] bytes = bytestream.toByteArray();
1775        File dir = new File(dirname);
1776        File file = makeFilename(name, dir);
1777        new File(file.getParent()).mkdirs();
1778        try {
1779            FileOutputStream o = new FileOutputStream(file);
1780            o.write(bytes);
1781            o.close();
1782        } catch (Throwable JavaDoc t) { t.printStackTrace(); }
1783    }
1784
1785    private static File makeFilename(String JavaDoc name, File dir) {
1786        int index = name.indexOf(".");
1787        if (index == -1)
1788            return new File(dir, name+".class");
1789
1790        return makeFilename(name.substring(index+1, name.length()),
1791                            new File(dir, name.substring(0, index)));
1792    }
1793    
1794    private static boolean abstract_issubclass(PyObject derived,PyObject cls) {
1795        if (derived == cls)
1796            return true;
1797        PyObject bases = derived.__findattr__("__bases__");
1798        if (bases == null)
1799            return false;
1800        for (int i = 0; i < bases.__len__(); i++) {
1801            if (abstract_issubclass(bases.__getitem__(i),cls))
1802                return true;
1803        }
1804        return false;
1805    }
1806        
1807    public static boolean isInstance(PyObject obj, PyObject cls) {
1808        if (cls instanceof PyType) {
1809            PyType objtype = obj.getType();
1810            if (objtype == cls)
1811                return true;
1812            return objtype.isSubType((PyType) cls);
1813        } else if (cls instanceof PyClass) {
1814            if (!(obj instanceof PyInstance))
1815                return false;
1816            return ((PyClass) obj.fastGetClass()).isSubClass((PyClass) cls);
1817        } else if (cls.getClass() == PyTuple.class) {
1818            for (int i = 0; i < cls.__len__(); i++) {
1819                if (isInstance(obj, cls.__getitem__(i)))
1820                    return true;
1821            }
1822            return false;
1823        } else {
1824            if (cls.__findattr__("__bases__") == null)
1825                throw Py.TypeError(
1826                    "isinstance() arg 2 must be a class, type,"
1827                        + " or tuple of classes and types");
1828            PyObject ocls = obj.__findattr__("__class__");
1829            if (ocls == null)
1830                return false;
1831            return abstract_issubclass(ocls, cls);
1832        }
1833    }
1834    
1835    public static boolean isSubClass(PyObject derived,PyObject cls) {
1836        if (derived instanceof PyType && cls instanceof PyType) {
1837            if (derived == cls) return true;
1838            return ((PyType)derived).isSubType((PyType)cls);
1839        } else if (cls instanceof PyClass && derived instanceof PyClass) {
1840            return ((PyClass)derived).isSubClass((PyClass)cls);
1841        } else if (cls.getClass() == PyTuple.class) {
1842            for (int i = 0; i < cls.__len__(); i++) {
1843                if (isSubClass(derived, cls.__getitem__(i)))
1844                    return true;
1845            }
1846            return false;
1847        } else {
1848            if (derived.__findattr__("__bases__") == null)
1849                throw Py.TypeError(
1850                    "issubclass() arg 1 must be a class");
1851            if (cls.__findattr__("__bases__") == null)
1852                throw Py.TypeError(
1853                    "issubclass() arg 2 must be a class, type,"
1854                        + " or tuple of classes and types");
1855            return abstract_issubclass(derived,cls);
1856        }
1857    }
1858
1859    static PyObject[] make_array(PyObject o) {
1860        if (o instanceof PyTuple)
1861            return ((PyTuple)o).getArray();
1862    
1863        PyObject iter = o.__iter__();
1864    
1865        // Guess result size and allocate space.
1866
int n = 10;
1867        try {
1868            n = o.__len__();
1869        } catch (PyException exc) { }
1870    
1871        PyObject[] objs= new PyObject[n];
1872    
1873        int i;
1874        for (i = 0; ; i++) {
1875            PyObject item = iter.__iternext__();
1876            if (item == null)
1877                break;
1878            if (i >= n) {
1879                if (n < 500) {
1880                    n += 10;
1881                } else {
1882                    n += 100;
1883                }
1884                PyObject[] newobjs = new PyObject[n];
1885                System.arraycopy(objs, 0, newobjs, 0, objs.length);
1886                objs = newobjs;
1887            }
1888            objs[i] = item;
1889        }
1890    
1891        // Cut back if guess was too large.
1892
if (i < n) {
1893            PyObject[] newobjs = new PyObject[i];
1894            System.arraycopy(objs, 0, newobjs, 0, i);
1895            objs = newobjs;
1896        }
1897        return objs;
1898    }
1899    
1900}
1901
1902/** @deprecated **/
1903class FixedFileWrapper extends StdoutWrapper {
1904    private PyObject file;
1905    public FixedFileWrapper(PyObject file) {
1906        name = "fixed file";
1907        this.file = file;
1908
1909        if (file instanceof PyJavaInstance) {
1910            Object JavaDoc tmp = file.__tojava__(OutputStream.class);
1911            if ((tmp != Py.NoConversion) && (tmp != null)) {
1912                OutputStream os = (OutputStream)tmp;
1913                this.file = new PyFile(os, "<java OutputStream>");
1914            } else {
1915                tmp = file.__tojava__(Writer.class);
1916                if ((tmp != Py.NoConversion) && (tmp != null)) {
1917                    Writer w = (Writer)tmp;
1918                    this.file = new PyFile(w, "<java Writer>");
1919                }
1920            }
1921        }
1922    }
1923
1924    protected PyObject myFile() {
1925        return file;
1926    }
1927}
1928
1929/**
1930 * A code object wrapper for a python function.
1931 */

1932class JavaCode extends PyCode {
1933    private PyObject func;
1934
1935    public JavaCode(PyObject func) {
1936        this.func = func;
1937        if (func instanceof PyReflectedFunction)
1938            this.co_name = ((PyReflectedFunction) func).__name__;
1939    }
1940
1941    public PyObject call(PyFrame frame, PyObject closure) {
1942        System.out.println("call #1");
1943        return Py.None;
1944    }
1945
1946    public PyObject call(PyObject args[], String JavaDoc keywords[],
1947                         PyObject globals, PyObject[] defaults,
1948                         PyObject closure)
1949    {
1950        return func.__call__(args, keywords);
1951    }
1952
1953    public PyObject call(PyObject self, PyObject args[], String JavaDoc keywords[],
1954                         PyObject globals, PyObject[] defaults,
1955                         PyObject closure)
1956    {
1957        return func.__call__(self, args, keywords);
1958    }
1959
1960    public PyObject call(PyObject globals, PyObject[] defaults,
1961                         PyObject closure)
1962    {
1963        return func.__call__();
1964    }
1965
1966    public PyObject call(PyObject arg1, PyObject globals,
1967                         PyObject[] defaults, PyObject closure)
1968    {
1969        return func.__call__(arg1);
1970    }
1971
1972    public PyObject call(PyObject arg1, PyObject arg2, PyObject globals,
1973                         PyObject[] defaults, PyObject closure)
1974    {
1975        return func.__call__(arg1, arg2);
1976    }
1977
1978    public PyObject call(PyObject arg1, PyObject arg2, PyObject arg3,
1979                         PyObject globals, PyObject[] defaults,
1980                         PyObject closure)
1981    {
1982        return func.__call__(arg1, arg2, arg3);
1983    }
1984}
1985
1986/**
1987 * A function object wrapper for a java method which comply with the
1988 * PyArgsKeywordsCall standard.
1989 */

1990class JavaFunc extends PyObject {
1991     java.lang.reflect.Method JavaDoc method;
1992
1993     public JavaFunc(java.lang.reflect.Method JavaDoc method) {
1994         this.method = method;
1995     }
1996
1997     public PyObject __call__(PyObject[] args, String JavaDoc[] kws) {
1998          Object JavaDoc[] margs = new Object JavaDoc[] { args, kws };
1999          try {
2000              return Py.java2py(method.invoke(null, margs));
2001          } catch (Throwable JavaDoc t) {
2002              throw Py.JavaError(t);
2003          }
2004     }
2005
2006    public PyObject _doget(PyObject container) {
2007        return _doget(container, null);
2008    }
2009
2010    public PyObject _doget(PyObject container, PyObject wherefound) {
2011        if (container == null)
2012            return this;
2013        return new PyMethod(container, this, wherefound);
2014    }
2015
2016    public boolean _doset(PyObject container) {
2017        throw Py.TypeError("java function not settable: "+method.getName());
2018    }
2019}
2020
Popular Tags