KickJava   Java API By Example, From Geeks To Geeks.

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


1 // Copyright (c) Corporation for National Research Initiatives
2
package org.python.core;
3
4 import java.util.Hashtable JavaDoc;
5
6 class BuiltinFunctions extends PyBuiltinFunctionSet
7 {
8     public BuiltinFunctions(String JavaDoc name, int index, int argcount) {
9         super(name, index, argcount, argcount, false, null);
10     }
11
12     public BuiltinFunctions(String JavaDoc name, int index, int minargs, int maxargs){
13         super(name, index, minargs, maxargs, false, null);
14     }
15
16     public PyObject __call__() {
17         switch (index) {
18         case 4:
19             return __builtin__.globals();
20         default:
21             throw argCountError(0);
22         }
23     }
24
25     public PyObject __call__(PyObject arg1) {
26         switch (index) {
27         case 0:
28             return Py.newString(__builtin__.chr(
29                 Py.py2int(arg1, "chr(): 1st arg can't be coerced to int")));
30         case 1:
31             return Py.newInteger(__builtin__.len(arg1));
32         case 2:
33             return __builtin__.range(
34                 Py.py2int(arg1, "range(): 1st arg can't be coerced to int"));
35         case 3:
36             return Py.newInteger(__builtin__.ord(
37                 Py.py2char(arg1, "ord(): 1st arg can't be coerced to char")));
38         case 5:
39             return __builtin__.hash(arg1);
40         case 8:
41             return __builtin__.tuple(arg1);
42         case 11:
43             return Py.newInteger(__builtin__.id(arg1));
44         case 12:
45             return __builtin__.sum(arg1);
46         default:
47             throw argCountError(1);
48         }
49     }
50
51     public PyObject __call__(PyObject arg1, PyObject arg2) {
52         switch (index) {
53         case 2:
54             return __builtin__.range(
55                 Py.py2int(arg1, "range(): 1st arg can't be coerced to int"),
56                 Py.py2int(arg2, "range(): 2nd arg can't be coerced to int"));
57         case 6:
58             return Py.newInteger(__builtin__.cmp(arg1, arg2));
59         case 9:
60             return __builtin__.apply(arg1, arg2);
61         case 10:
62             return Py.newBoolean(__builtin__.isinstance(arg1, arg2));
63         case 12:
64             return __builtin__.sum(arg1, arg2);
65         default:
66             throw argCountError(2);
67         }
68     }
69
70     public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) {
71         switch (index) {
72         case 2:
73             return __builtin__.range(
74                 Py.py2int(arg1, "range(): 1st arg can't be coerced to int"),
75                 Py.py2int(arg2, "range(): 2nd arg can't be coerced to int"),
76                 Py.py2int(arg3, "range(): 3rd arg can't be coerced to int"));
77         case 9:
78             try {
79                 if (arg3 instanceof PyStringMap) {
80                     PyDictionary d = new PyDictionary();
81                     d.update((PyStringMap) arg3);
82                     arg3 = d;
83                 }
84
85                 // this catches both casts of arg3 to a PyDictionary, and
86
// all casts of keys in the dictionary to PyStrings inside
87
// apply(PyObject, PyObject, PyDictionary)
88
PyDictionary d = (PyDictionary)arg3;
89                 return __builtin__.apply(arg1, arg2, d);
90             }
91             catch (ClassCastException JavaDoc e) {
92                 throw Py.TypeError("apply() 3rd argument must be a "+
93                                    "dictionary with string keys");
94             }
95         default:
96             throw argCountError(3);
97         }
98     }
99 }
100
101 /**
102  * The builtin module. All builtin functions are defined here
103  */

104 public class __builtin__ implements ClassDictInit
105 {
106     /** <i>Internal use only. Do not call this method explicit.</i> */
107     public static void classDictInit(PyObject dict) {
108         /* newstyle */
109
110         dict.__setitem__("object", PyType.fromClass(PyObject.class));
111         dict.__setitem__("type", PyType.fromClass(PyType.class));
112         dict.__setitem__("int", PyType.fromClass(PyInteger.class));
113         dict.__setitem__("enumerate", PyType.fromClass(PyEnumerate.class));
114         dict.__setitem__("float", PyType.fromClass(PyFloat.class));
115         dict.__setitem__("long", PyType.fromClass(PyLong.class));
116         dict.__setitem__("complex", PyType.fromClass(PyComplex.class));
117         dict.__setitem__("dict", PyType.fromClass(PyDictionary.class));
118         dict.__setitem__("list", PyType.fromClass(PyList.class));
119         dict.__setitem__("tuple", PyType.fromClass(PyTuple.class));
120
121         dict.__setitem__("property", PyType.fromClass(PyProperty.class));
122         dict.__setitem__("staticmethod", PyType.fromClass(PyStaticMethod.class));
123         dict.__setitem__("classmethod", PyType.fromClass(PyClassMethod.class));
124         dict.__setitem__("super", PyType.fromClass(PySuper.class));
125         dict.__setitem__("str", PyType.fromClass(PyString.class));
126         dict.__setitem__("unicode", PyType.fromClass(PyUnicode.class));
127         dict.__setitem__("file", PyType.fromClass(PyFile.class));
128
129         /* - */
130
131         dict.__setitem__("None", Py.None);
132         dict.__setitem__("NotImplemented", Py.NotImplemented);
133         dict.__setitem__("Ellipsis", Py.Ellipsis);
134         dict.__setitem__("True", Py.One);
135         dict.__setitem__("False", Py.Zero);
136
137         // Work in debug mode by default
138
// Hopefully add -O option in the future to change this
139
dict.__setitem__("__debug__", Py.One);
140
141         dict.__setitem__("chr", new BuiltinFunctions("chr", 0, 1));
142         dict.__setitem__("len", new BuiltinFunctions("len", 1, 1));
143         dict.__setitem__("range", new BuiltinFunctions("range", 2, 1, 3));
144         dict.__setitem__("ord", new BuiltinFunctions("ord", 3, 1));
145         dict.__setitem__("globals", new BuiltinFunctions("globals", 4, 0));
146         dict.__setitem__("hash", new BuiltinFunctions("hash", 5, 1));
147         dict.__setitem__("cmp", new BuiltinFunctions("cmp", 6, 2));
148         dict.__setitem__("apply", new BuiltinFunctions("apply", 9, 2, 3));
149         dict.__setitem__("isinstance",
150                                   new BuiltinFunctions("isinstance", 10, 2));
151         dict.__setitem__("id", new BuiltinFunctions("id", 11, 1));
152         dict.__setitem__("sum", new BuiltinFunctions("sum", 12, 1, 2));
153         dict.__setitem__("__import__", new ImportFunction());
154
155         dict.__delitem__("execfile_flags"); // -execfile_flags
156
}
157
158     public static PyObject abs(PyObject o) {
159         if (o.isNumberType())
160             return o.__abs__();
161         throw Py.TypeError("bad operand type for abs()");
162     }
163
164     public static PyObject apply(PyObject o, PyObject args) {
165         return o.__call__(Py.make_array(args));
166     }
167
168     public static PyObject apply(PyObject o, PyObject args,
169                                  PyDictionary kws) {
170         PyObject[] a;
171         String JavaDoc[] kw;
172         Hashtable JavaDoc table = kws.table;
173         if (table.size() > 0) {
174             java.util.Enumeration JavaDoc ek = table.keys();
175             java.util.Enumeration JavaDoc ev = table.elements();
176             int n = table.size();
177             kw = new String JavaDoc[n];
178             PyObject[] aargs = Py.make_array(args);
179             a = new PyObject[n+aargs.length];
180             System.arraycopy(aargs, 0, a, 0, aargs.length);
181             int offset = aargs.length;
182
183             for (int i=0; i<n; i++) {
184                 kw[i] = ((PyString)ek.nextElement()).internedString();
185                 a[i+offset] = (PyObject)ev.nextElement();
186             }
187             return o.__call__(a, kw);
188         } else {
189             return apply(o, args);
190         }
191     }
192
193     public static PyObject bool(PyObject o) {
194         return (o == null ? Py.Zero : o.__nonzero__() ? Py.One : Py.Zero);
195     }
196
197     public static boolean callable(PyObject o) {
198         return o.__findattr__("__call__") != null;
199     }
200
201     public static char unichr(int i) {
202         return chr(i);
203     }
204
205     public static char chr(int i) {
206         if (i < 0 || i > 65535)
207             throw Py.ValueError("chr() arg not in range(65535)");
208         return (char)i;
209     }
210
211     public static int cmp(PyObject x, PyObject y) {
212         return x._cmp(y);
213     }
214
215     public static PyTuple coerce(PyObject o1, PyObject o2) {
216         PyObject[] result = o1._coerce(o2);
217         if (result != null)
218             return new PyTuple(result);
219         throw Py.TypeError("number coercion failed");
220     }
221
222     public static PyCode compile(String JavaDoc data, String JavaDoc filename, String JavaDoc type) {
223         return Py.compile_flags(data,filename,type,Py.getCompilerFlags());
224     }
225
226     public static PyCode compile(String JavaDoc data, String JavaDoc filename, String JavaDoc type,
227                                  int flags, boolean dont_inherit) {
228         if ((flags&~PyTableCode.CO_ALL_FEATURES) != 0)
229             throw Py.ValueError("compile(): unrecognised flags");
230         return Py.compile_flags(data,filename,type,Py.getCompilerFlags(flags,dont_inherit));
231     }
232
233     public static void delattr(PyObject o, PyString n) {
234         o.__delattr__(n);
235     }
236
237     public static PyObject dir(PyObject o) {
238         PyList ret = (PyList)o.__dir__();
239         ret.sort();
240         return ret;
241     }
242
243     public static PyObject dir() {
244         PyObject l = locals();
245         PyList ret;
246
247         if (l instanceof PyStringMap)
248             ret = ((PyStringMap)l).keys();
249         if (l instanceof PyDictionary)
250             ret = ((PyDictionary)l).keys();
251
252         ret = (PyList)l.invoke("keys");
253         ret.sort();
254         return ret;
255     }
256
257     public static PyObject divmod(PyObject x, PyObject y) {
258         return x._divmod(y);
259     }
260
261     public static PyEnumerate enumerate(PyObject seq) {
262         return new PyEnumerate(seq);
263     }
264
265     public static PyObject eval(PyObject o, PyObject globals, PyObject locals)
266     {
267         PyCode code;
268         if (o instanceof PyCode)
269             code = (PyCode)o;
270         else {
271             if (o instanceof PyString) {
272                 code = compile(o.toString(), "<string>", "eval");
273             } else
274                 throw Py.TypeError(
275                     "eval: argument 1 must be string or code object");
276         }
277         return Py.runCode(code, locals, globals);
278     }
279
280     public static PyObject eval(PyObject o, PyObject globals) {
281         return eval(o, globals, globals);
282     }
283
284     public static PyObject eval(PyObject o) {
285         return eval(o, null, null);
286     }
287
288     public static void execfile(String JavaDoc name, PyObject globals,
289                                 PyObject locals)
290     {
291         execfile_flags(name,globals,locals,Py.getCompilerFlags());
292     }
293
294
295     public static void execfile_flags(String JavaDoc name, PyObject globals,
296                                 PyObject locals,CompilerFlags cflags)
297     {
298         java.io.FileInputStream JavaDoc file;
299         try {
300             file = new java.io.FileInputStream JavaDoc(name);
301         } catch (java.io.FileNotFoundException JavaDoc e) {
302             throw Py.IOError(e);
303         }
304         PyCode code;
305
306         try {
307             code = Py.compile_flags(file, name, "exec",cflags);
308         } finally {
309             try {
310                 file.close();
311             } catch (java.io.IOException JavaDoc e) {
312                 throw Py.IOError(e);
313             }
314         }
315         Py.runCode(code, locals, globals);
316     }
317
318     public static void execfile(String JavaDoc name, PyObject globals) {
319         execfile(name, globals, globals);
320     }
321
322     public static void execfile(String JavaDoc name) {
323         execfile(name, null, null);
324     }
325
326     public static PyObject filter(PyObject f, PyString s) {
327         if (f == Py.None)
328             return s;
329         PyObject[] args = new PyObject[1];
330         char[] chars = s.toString().toCharArray();
331         int i;
332         int j;
333         int n = chars.length;
334         for(i=0, j=0; i<n; i++) {
335             args[0] = Py.makeCharacter(chars[i]);
336             if (!f.__call__(args).__nonzero__())
337                 continue;
338             chars[j++] = chars[i];
339         }
340         return new PyString(new String JavaDoc(chars, 0, j));
341     }
342
343
344     public static PyObject filter(PyObject f, PyObject l) {
345         PyList list = new PyList();
346         PyObject iter = l.__iter__();
347         for (PyObject item = null; (item = iter.__iternext__()) != null; ) {
348             if (f == Py.None) {
349                 if (!item.__nonzero__())
350                     continue;
351             } else {
352                 if (!f.__call__(item).__nonzero__())
353                     continue;
354             }
355             list.append(item);
356         }
357         if (l instanceof PyTuple)
358             return tuple(list);
359         return list;
360     }
361
362     public static PyObject getattr(PyObject o, PyString n) {
363         return o.__getattr__(n);
364     }
365
366     public static PyObject getattr(PyObject o, PyString n, PyObject def) {
367         PyObject val = o.__findattr__(n);
368         if (val != null)
369              return val;
370         return def;
371     }
372
373     public static PyObject globals() {
374         return Py.getFrame().f_globals;
375     }
376
377     public static boolean hasattr(PyObject o, PyString n) {
378         try {
379             return o.__findattr__(n) != null;
380         } catch (PyException exc) {
381             if (Py.matchException(exc, Py.AttributeError))
382                 return false;
383             throw exc;
384         }
385     }
386
387     public static PyInteger hash(PyObject o) {
388         return o.__hash__();
389     }
390
391     public static PyString hex(PyObject o) {
392         return o.__hex__();
393     }
394
395     public static long id(PyObject o) {
396         return Py.id(o);
397     }
398
399
400     public static PyObject input(PyObject prompt) {
401         String JavaDoc line = raw_input(prompt);
402         return eval(new PyString(line));
403     }
404
405     public static PyObject input() {
406         return input(new PyString(""));
407     }
408
409     private static PyStringMap internedStrings;
410     public static PyString intern(PyString s) {
411         if (internedStrings == null) {
412             internedStrings = new PyStringMap();
413         }
414
415         String JavaDoc istring = s.internedString();
416         PyObject ret = internedStrings.__finditem__(istring);
417         if (ret != null)
418             return (PyString)ret;
419
420         internedStrings.__setitem__(istring, s);
421         return s;
422     }
423
424     // xxx find where used, modify with more appropriate if necessary
425
public static boolean isinstance(PyObject obj, PyObject cls) {
426         return Py.isInstance(obj,cls);
427     }
428
429     // xxx find where used, modify with more appropriate if necessary
430
public static boolean issubclass(PyObject derived, PyObject cls) {
431         return Py.isSubClass(derived,cls);
432     }
433
434     public static int len(PyObject o) {
435         try {
436             return o.__len__();
437         }
438         catch (PyException e) {
439             // Make this work like CPython where
440
//
441
// a = 7; len(a) raises a TypeError,
442
// a.__len__() raises an AttributeError
443
// and
444
// class F: pass
445
// f = F(); len(f) also raises an AttributeError
446
//
447
// Testing the type of o feels unclean though
448
if (e.type == Py.AttributeError && !(o instanceof PyInstance))
449                 throw Py.TypeError("len() of unsized object");
450             else
451                 throw e;
452         }
453     }
454
455     public static PyObject locals() {
456         return Py.getFrame().getf_locals();
457     }
458
459     public static PyObject map(PyObject[] argstar) {
460         int n = argstar.length-1;
461         if (n < 1)
462             throw Py.TypeError("map requires at least two arguments");
463         PyObject element;
464         PyObject f = argstar[0];
465         PyList list = new PyList();
466         PyObject[] args = new PyObject[n];
467         PyObject[] iters = new PyObject[n];
468
469         for (int j = 0; j < n; j++) {
470             iters[j] = Py.iter(argstar[j+1], "argument " + (j+1) +
471                                " to map() must support iteration");
472         }
473
474         while (true) {
475             boolean any_items = false;
476             for(int j = 0; j < n; j++) {
477                 if ((element = iters[j].__iternext__()) != null) {
478                     args[j] = element;
479                     any_items = true;
480                 } else {
481                     args[j] = Py.None;
482                 }
483             }
484             if (!any_items)
485                 break;
486             if (f == Py.None) {
487                 if (n == 1) {
488                     list.append(args[0]);
489                 } else {
490                     list.append(new PyTuple((PyObject[])args.clone()));
491                 }
492             } else {
493                 list.append(f.__call__(args));
494             }
495         }
496         return list;
497     }
498
499
500     // I've never been happy with max and min builtin's...
501

502     public static PyObject max(PyObject[] l) {
503         if (l.length == 1)
504             return max(l[0]);
505         else return max(new PyTuple(l));
506     }
507
508     private static PyObject max(PyObject o) {
509         PyObject max = null;
510         PyObject iter = o.__iter__();
511         for (PyObject item; (item = iter.__iternext__()) != null; ) {
512             if (max == null || item._gt(max).__nonzero__())
513                 max = item;
514         }
515         if (max == null)
516             throw Py.ValueError("max of empty sequence");
517         return max;
518     }
519
520     public static PyObject min(PyObject[] l) {
521         if (l.length == 1)
522             return min(l[0]);
523         else return min(new PyTuple(l));
524     }
525
526     private static PyObject min(PyObject o) {
527         PyObject min = null;
528         PyObject iter = o.__iter__();
529         for (PyObject item; (item = iter.__iternext__()) != null; ) {
530             if (min == null || item._lt(min).__nonzero__())
531                 min = item;
532         }
533         if (min == null)
534             throw Py.ValueError("min of empty sequence");
535         return min;
536     }
537
538     public static PyString oct(PyObject o) {
539         return o.__oct__();
540     }
541
542     /**
543      * Open a file read-only.
544      * @param name the file to open.
545      * @exception java.io.IOException
546      */

547     public static PyFile open(String JavaDoc name) throws java.io.IOException JavaDoc {
548         return new PyFile(name, "r", -1);
549     }
550
551     /**
552      * Open a file with the specified mode.
553      * @param name name of the file to open.
554      * @param mode open mode of the file. Use "r", "w", "r+", "w+" and "a".
555      * @exception java.io.IOException
556      */

557     public static PyFile open(String JavaDoc name, String JavaDoc mode)
558         throws java.io.IOException JavaDoc
559     {
560         return new PyFile(name, mode, -1);
561     }
562
563     /**
564      * Open a file with the specified mode and buffer size.
565      * @param name name of the file to open.
566      * @param mode open mode of the file. Use "r", "w", "r+", "w+" and "a".
567      * @param bufsize size of the internal buffer. Not currently used.
568      * @exception java.io.IOException
569      */

570     public static PyFile open(String JavaDoc name, String JavaDoc mode, int bufsize)
571         throws java.io.IOException JavaDoc
572     {
573         return new PyFile(name, mode, bufsize);
574     }
575
576     //XXX: remove once we're sure this isn't needed
577
/*
578      * Open a file read-only.
579      * @param name the file to open.
580      * @exception java.io.IOException
581      */

582     //public static PyFile file(String name) throws java.io.IOException {
583
// return open(name);
584
//}
585

586     /*
587      * Open a file with the specified mode.
588      * @param name name of the file to open.
589      * @param mode open mode of the file. Use "r", "w", "r+", "w+" and "a".
590      * @exception java.io.IOException
591      */

592     //public static PyFile file(String name, String mode)
593
// throws java.io.IOException
594
//{
595
// return open(name, mode);
596
//}
597

598     /*
599      * Open a file with the specified mode and buffer size.
600      * @param name name of the file to open.
601      * @param mode open mode of the file. Use "r", "w", "r+", "w+" and "a".
602      * @param bufsize size of the internal buffer. Not currently used.
603      * @exception java.io.IOException
604      */

605     //public static PyFile file(String name, String mode, int bufsize)
606
// throws java.io.IOException
607
//{
608
// return open(name, mode, bufsize);
609
//}
610

611
612     public static final int ord(char c) {
613         return (int)(c);
614     }
615
616     public static PyObject pow(PyObject x, PyObject y) {
617         return x._pow(y);
618     }
619
620     private static boolean coerce(PyObject[] objs) {
621         PyObject x = objs[0];
622         PyObject y = objs[1];
623         PyObject[] result;
624         result = x._coerce(y);
625         if (result != null) {
626             objs[0] = result[0];
627             objs[1] = result[1];
628             return true;
629         }
630         result = y._coerce(x);
631         if (result != null) {
632             objs[0] = result[1];
633             objs[1] = result[0];
634             return true;
635         }
636         return false;
637     }
638
639     public static PyObject pow(PyObject xi, PyObject yi, PyObject zi) {
640         PyObject x=xi;
641         PyObject y=yi;
642         PyObject z=zi;
643
644         boolean doit=false;
645
646         PyObject[] tmp = new PyObject[2];
647
648         tmp[0] = x;
649         tmp[1] = y;
650         if (coerce(tmp)) {
651             x = tmp[0];
652             y = tmp[1];
653             tmp[1] = z;
654             if (coerce(tmp)) {
655                 x = tmp[0];
656                 z = tmp[1];
657                 tmp[0] = y;
658                 if (coerce(tmp)) {
659                     z = tmp[1];
660                     y = tmp[0];
661                     doit=true;
662                 }
663             }
664         } else {
665             tmp[1] = z;
666             if (coerce(tmp)) {
667                 x=tmp[0];
668                 z=tmp[1];
669                 tmp[0] = y;
670                 if (coerce(tmp)) {
671                     y=tmp[0]; z = tmp[1];
672                     tmp[1] = x;
673                     if (coerce(tmp)) {
674                         x=tmp[1];
675                         y=tmp[0];
676                         doit = true;
677                     }
678                 }
679             }
680         }
681
682         if (x.getType() == y.getType() && x.getType() == z.getType()) {
683             x = x.__pow__(y, z);
684             if (x != null)
685                 return x;
686         }
687         throw Py.TypeError("__pow__ not defined for these operands");
688     }
689
690     public static PyObject range(int start, int stop, int step) {
691         if (step == 0)
692             throw Py.ValueError("zero step for range()");
693         int n;
694         if (step > 0)
695             n = (stop-start+step-1)/step;
696         else
697             n = (stop-start+step+1)/step;
698
699         if (n <= 0)
700             return new PyList();
701         PyObject[] l = new PyObject[n];
702         int j=start;
703         for (int i=0; i<n; i++) {
704             l[i] = Py.newInteger(j);
705             j+= step;
706         }
707         return new PyList(l);
708     }
709
710     public static PyObject range(int n) {
711         return range(0,n,1);
712     }
713
714     public static PyObject range(int start, int stop) {
715         return range(start,stop,1);
716     }
717
718     private static PyString readline(PyObject file) {
719         if (file instanceof PyFile) {
720             return new PyString(((PyFile)file).readline());
721         } else {
722             PyObject ret = file.invoke("readline");
723             if (!(ret instanceof PyString)) {
724                 throw Py.TypeError("object.readline() returned non-string");
725             }
726             return (PyString)ret;
727         }
728     }
729
730     public static String JavaDoc raw_input(PyObject prompt) {
731         Py.print(prompt);
732         PyObject stdin = Py.getSystemState().stdin;
733         String JavaDoc data = readline(stdin).toString();
734         if (data.endsWith("\n")) {
735             return data.substring(0, data.length()-1);
736         } else {
737             if (data.length() == 0) {
738                 throw Py.EOFError("raw_input()");
739             }
740         }
741         return data;
742     }
743
744     public static String JavaDoc raw_input() {
745         return raw_input(new PyString(""));
746     }
747
748     public static PyObject reduce(PyObject f, PyObject l, PyObject z) {
749         PyObject result = z;
750         PyObject iter = Py.iter(l, "reduce() arg 2 must support iteration");
751
752         for (PyObject item; (item = iter.__iternext__()) != null; ) {
753             if (result == null)
754                 result = item;
755             else
756                 result = f.__call__(result, item);
757         }
758         if (result == null) {
759             throw Py.TypeError(
760                     "reduce of empty sequence with no initial value");
761         }
762         return result;
763     }
764
765     public static PyObject reduce(PyObject f, PyObject l) {
766         return reduce(f, l, null);
767     }
768
769     public static PyObject reload(PyModule o) {
770         return imp.reload(o);
771     }
772     public static PyObject reload(PyJavaClass o) {
773         return imp.reload(o);
774     }
775
776     public static PyString repr(PyObject o) {
777         return o.__repr__();
778     }
779
780     //This seems awfully special purpose...
781
public static PyFloat round(double f, int digits) {
782         boolean neg = f < 0;
783         double multiple = Math.pow(10., digits);
784         if (neg)
785             f = -f;
786         double tmp = Math.floor(f*multiple+0.5);
787         if (neg)
788             tmp = -tmp;
789         return new PyFloat(tmp/multiple);
790     }
791
792     public static PyFloat round(double f) {
793         return round(f, 0);
794     }
795
796     public static void setattr(PyObject o, PyString n, PyObject v) {
797         o.__setattr__(n, v);
798     }
799
800     public static PySlice slice(PyObject start, PyObject stop,
801                                 PyObject step)
802     {
803         return new PySlice(start, stop, step);
804     }
805
806     public static PySlice slice(PyObject start, PyObject stop) {
807         return slice(start, stop, Py.None);
808     }
809
810     public static PySlice slice(PyObject stop) {
811         return slice(Py.None, stop, Py.None);
812     }
813
814     public static PyObject iter(PyObject obj) {
815         return obj.__iter__();
816     }
817
818     public static PyObject iter(PyObject callable, PyObject sentinel) {
819         return new PyCallIter(callable, sentinel);
820     }
821
822     public static PyObject sum(PyObject seq, PyObject result) {
823
824         if(result instanceof PyString) {
825             throw Py.TypeError("sum() can't sum strings [use ''.join(seq) instead]");
826         }
827
828         PyObject item;
829         PyObject iter = seq.__iter__();
830         while((item = iter.__iternext__()) != null) {
831             result = result._add(item);
832         }
833         return result;
834     }
835
836     public static PyObject sum(PyObject seq) {
837         return sum(seq, Py.Zero);
838     }
839
840     /*
841     public static PyString unicode(PyObject v) {
842         return unicode(v.__str__(), null, null);
843     }
844
845     public static PyString unicode(PyString v, String encoding) {
846         return unicode(v, encoding, null);
847     }
848
849     public static PyString unicode(PyString v, String encoding,
850                                   String errors)
851     {
852         return new PyString(codecs.decode(v, encoding, errors));
853     }
854     */

855     public static PyTuple tuple(PyObject o) {
856         if (o instanceof PyTuple)
857             return (PyTuple)o;
858         if (o instanceof PyList) {
859             // always make a copy, otherwise the tuple will share the
860
// underlying data structure with the list object, which
861
// renders the tuple mutable!
862
PyList l = (PyList)o;
863             PyObject[] a = new PyObject[l.size()];
864             System.arraycopy(l.getArray(), 0, a, 0, a.length);
865             return new PyTuple(a);
866         }
867         return new PyTuple(Py.make_array(o));
868     }
869
870     public static PyType type(PyObject o) {
871         return o.getType();
872     }
873
874     public static PyObject vars(PyObject o) {
875         return o.__getattr__("__dict__");
876     }
877
878     public static PyObject vars() {
879         return locals();
880     }
881
882     public static PyObject xrange(int start, int stop, int step) {
883         return new PyXRange(start, stop, step);
884     }
885
886     public static PyObject xrange(int n) {
887         return xrange(0,n,1);
888     }
889
890     public static PyObject xrange(int start, int stop) {
891         return xrange(start,stop,1);
892     }
893
894     public static PyString __doc__zip = new PyString(
895       "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n"+
896       "\n"+
897       "Return a list of tuples, where each tuple contains the i-th element\n"+
898       "from each of the argument sequences. The returned list is\n"+
899       "truncated in length to the length of the shortest argument sequence."
900     );
901
902     public static PyObject zip(PyObject[] argstar) {
903         int itemsize = argstar.length;
904         if (itemsize < 1)
905             throw Py.TypeError("zip requires at least one sequence");
906
907         // Type check the arguments; they must be sequences. Might as well
908
// cache the __iter__() methods.
909
PyObject[] iters = new PyObject[itemsize];
910
911         for (int j=0; j < itemsize; j++) {
912             PyObject iter = argstar[j].__iter__();
913             if (iter == null) {
914                 throw Py.TypeError("zip argument #" + (j + 1) +
915                                    " must support iteration");
916             }
917             iters[j] = iter;
918         }
919
920         PyList ret = new PyList();
921
922         for (int i=0;; i++) {
923             PyObject[] next = new PyObject[itemsize];
924             PyObject item;
925
926             for (int j=0; j < itemsize; j++) {
927                 try {
928                     item = iters[j].__iternext__();
929                 }
930                 catch (PyException e) {
931                     if (Py.matchException(e, Py.StopIteration))
932                         return ret;
933                     throw e;
934                 }
935                 if (item == null)
936                     return ret;
937                 next[j] = item;
938             }
939             ret.append(new PyTuple(next));
940         }
941     }
942
943     public static PyObject __import__(String JavaDoc name) {
944         return __import__(name, null, null, null);
945     }
946
947     public static PyObject __import__(String JavaDoc name, PyObject globals) {
948         return __import__(name, globals, null, null);
949     }
950
951     public static PyObject __import__(String JavaDoc name, PyObject globals,
952                                       PyObject locals) {
953         return __import__(name, globals, locals, null);
954     }
955
956     public static PyObject __import__(String JavaDoc name, PyObject globals,
957                                       PyObject locals, PyObject fromlist)
958     {
959         PyFrame frame = Py.getFrame();
960         if (frame == null)
961             return null;
962
963         PyObject builtins = frame.f_builtins;
964         if (builtins == null)
965             builtins = Py.getSystemState().builtins;
966
967         PyObject __import__ = builtins.__finditem__("__import__");
968         if (__import__ == null)
969             return null;
970
971         PyObject module = __import__.__call__(new PyObject[] {
972                 Py.newString(name),
973                 globals,
974                 locals,
975                 fromlist } );
976         return module;
977     }
978
979 }
980
981
982 class ImportFunction extends PyObject {
983     public ImportFunction() {}
984
985     public PyObject __call__(PyObject args[], String JavaDoc keywords[]) {
986         if (!(args.length < 1 || args[0] instanceof PyString))
987             throw Py.TypeError("first argument must be a string");
988         if (keywords.length > 0)
989             throw Py.TypeError("__import__() takes no keyword arguments");
990
991         int argc = args.length;
992         String JavaDoc module = args[0].__str__().toString();
993
994         PyObject globals = (argc > 1 && args[1] != null)
995             ? args[1] : null;
996         PyObject fromlist = (argc > 3 && args[3] != null)
997             ? args[3] : Py.EmptyTuple;
998
999         return load(module, globals, fromlist);
1000    }
1001
1002    private PyObject load(String JavaDoc module,
1003                          PyObject globals,
1004                          PyObject fromlist)
1005    {
1006        PyObject mod = imp.importName(module.intern(),
1007                                      fromlist.__len__() == 0,
1008                                      globals);
1009        return mod;
1010    }
1011
1012    public String JavaDoc toString() {
1013        return "<built-in function __import__>";
1014    }
1015}
1016
Popular Tags