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