// Copyright (c) Corporation for National Research Initiatives package org.python.core; import org.python.parser.SimpleNode; import java.util.Hashtable; import java.math.BigInteger; class BuiltinFunctions extends PyBuiltinFunctionSet { public BuiltinFunctions(String name, int index, int argcount) { super(name, index, argcount, argcount, false, null); } public BuiltinFunctions(String name, int index, int minargs, int maxargs){ super(name, index, minargs, maxargs, false, null); } public PyObject __call__() { switch (index) { case 4: return __builtin__.globals(); default: throw argCountError(0); } } public PyObject __call__(PyObject arg1) { switch (index) { case 0: return Py.newString(__builtin__.chr( Py.py2int(arg1, "chr(): 1st arg can't be coerced to int"))); case 1: return Py.newInteger(__builtin__.len(arg1)); case 2: return __builtin__.range( Py.py2int(arg1, "range(): 1st arg can't be coerced to int")); case 3: return Py.newInteger(__builtin__.ord( Py.py2char(arg1, "ord(): 1st arg can't be coerced to char"))); case 5: return __builtin__.hash(arg1); case 7: return __builtin__.list(arg1); case 8: return __builtin__.tuple(arg1); case 11: return Py.newInteger(__builtin__.id(arg1)); default: throw argCountError(1); } } public PyObject __call__(PyObject arg1, PyObject arg2) { switch (index) { case 2: return __builtin__.range( Py.py2int(arg1, "range(): 1st arg can't be coerced to int"), Py.py2int(arg2, "range(): 2nd arg can't be coerced to int")); case 6: return Py.newInteger(__builtin__.cmp(arg1, arg2)); case 9: return __builtin__.apply(arg1, arg2); case 10: return Py.newBoolean(__builtin__.isinstance(arg1, arg2)); default: throw argCountError(2); } } public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { switch (index) { case 2: return __builtin__.range( Py.py2int(arg1, "range(): 1st arg can't be coerced to int"), Py.py2int(arg2, "range(): 2nd arg can't be coerced to int"), Py.py2int(arg3, "range(): 3rd arg can't be coerced to int")); case 9: try { if (arg3 instanceof PyStringMap) { PyDictionary d = new PyDictionary(); d.update((PyStringMap) arg3); arg3 = d; } // this catches both casts of arg3 to a PyDictionary, and // all casts of keys in the dictionary to PyStrings inside // apply(PyObject, PyObject, PyDictionary) PyDictionary d = (PyDictionary)arg3; return __builtin__.apply(arg1, arg2, d); } catch (ClassCastException e) { throw Py.TypeError("apply() 3rd argument must be a "+ "dictionary with string keys"); } default: throw argCountError(3); } } } /** * The builtin module. All builtin functions are defined here */ public class __builtin__ implements ClassDictInit { /** Internal use only. Do not call this method explicit. */ public static void classDictInit(PyObject dict) { dict.__setitem__("None", Py.None); dict.__setitem__("NotImplemented", Py.NotImplemented); dict.__setitem__("Ellipsis", Py.Ellipsis); dict.__setitem__("True", Py.One); dict.__setitem__("False", Py.Zero); // Work in debug mode by default // Hopefully add -O option in the future to change this dict.__setitem__("__debug__", Py.One); dict.__setitem__("chr", new BuiltinFunctions("chr", 0, 1)); dict.__setitem__("len", new BuiltinFunctions("len", 1, 1)); dict.__setitem__("range", new BuiltinFunctions("range", 2, 1, 3)); dict.__setitem__("ord", new BuiltinFunctions("ord", 3, 1)); dict.__setitem__("globals", new BuiltinFunctions("globals", 4, 0)); dict.__setitem__("hash", new BuiltinFunctions("hash", 5, 1)); dict.__setitem__("cmp", new BuiltinFunctions("cmp", 6, 2)); dict.__setitem__("list", new BuiltinFunctions("list", 7, 1)); dict.__setitem__("tuple", new BuiltinFunctions("tuple", 8, 1)); dict.__setitem__("apply", new BuiltinFunctions("apply", 9, 2, 3)); dict.__setitem__("isinstance", new BuiltinFunctions("isinstance", 10, 2)); dict.__setitem__("id", new BuiltinFunctions("id", 11, 1)); dict.__setitem__("__import__", new ImportFunction()); dict.__delitem__("execfile_flags"); // -execfile_flags } public static PyObject abs(PyObject o) { if (o.isNumberType()) return o.__abs__(); throw Py.TypeError("bad operand type for abs()"); } public static PyObject apply(PyObject o, PyObject args) { return o.__call__(make_array(args)); } public static PyObject apply(PyObject o, PyObject args, PyDictionary kws) { PyObject[] a; String[] kw; Hashtable table = kws.table; if (table.size() > 0) { java.util.Enumeration ek = table.keys(); java.util.Enumeration ev = table.elements(); int n = table.size(); kw = new String[n]; PyObject[] aargs = make_array(args); a = new PyObject[n+aargs.length]; System.arraycopy(aargs, 0, a, 0, aargs.length); int offset = aargs.length; for (int i=0; i 65535) throw Py.ValueError("chr() arg not in range(65535)"); return (char)i; } public static int cmp(PyObject x, PyObject y) { return x._cmp(y); } public static PyTuple coerce(PyObject o1, PyObject o2) { Object ctmp; PyTuple ret; if (o1.__class__ == o2.__class__) { return new PyTuple(new PyObject[] {o1, o2}); } ctmp = o1.__coerce_ex__(o2); if (ctmp != null && ctmp != Py.None) { if (ctmp instanceof PyObject[]) { return new PyTuple((PyObject[])ctmp); } else { return new PyTuple(new PyObject[] {o1, (PyObject)ctmp}); } } ctmp = o2.__coerce_ex__(o1); if (ctmp != null && ctmp != Py.None) { if (ctmp instanceof PyObject[]) { return new PyTuple((PyObject[])ctmp); } else { return new PyTuple(new PyObject[] {(PyObject)ctmp, o2}); } } throw Py.TypeError("number coercion failed"); } public static PyCode compile(String data, String filename, String type) { return Py.compile_flags(data,filename,type,Py.getCompilerFlags()); } public static PyCode compile(String data, String filename, String type, int flags, boolean dont_inherit) { if ((flags&~PyTableCode.CO_ALL_FEATURES) != 0) throw Py.ValueError("compile(): unrecognised flags"); return Py.compile_flags(data,filename,type,Py.getCompilerFlags(flags,dont_inherit)); } public static PyComplex complex(PyObject real, PyObject imag) { if (real instanceof PyString) throw Py.TypeError("complex() can't take second arg" + " if first is a string"); if (imag instanceof PyString) throw Py.TypeError("complex() second arg can't be a string"); return (PyComplex)real.__complex__().__add__( imag.__complex__().__mul__(PyComplex.J)); } public static PyComplex complex(PyObject real) { return real.__complex__(); } public static void delattr(PyObject o, PyString n) { o.__delattr__(n); } public static PyObject dir(PyObject o) { PyList ret = (PyList)o.__dir__(); ret.sort(); return ret; } public static PyObject dir() { PyObject l = locals(); PyList ret; if (l instanceof PyStringMap) ret = ((PyStringMap)l).keys(); if (l instanceof PyDictionary) ret = ((PyDictionary)l).keys(); ret = (PyList)l.invoke("keys"); ret.sort(); return ret; } public static PyObject divmod(PyObject x, PyObject y) { return x._divmod(y); } public static PyObject eval(PyObject o, PyObject globals, PyObject locals) { PyCode code; if (o instanceof PyCode) code = (PyCode)o; else { if (o instanceof PyString) { // eval does not inherit co_nested code = Py.compile_flags(((PyString)o).toString(), "", "eval", null); } else throw Py.TypeError( "eval: argument 1 must be string or code object"); } return Py.runCode(code, locals, globals); } public static PyObject eval(PyObject o, PyObject globals) { return eval(o, globals, globals); } public static PyObject eval(PyObject o) { return eval(o, null, null); } public static void execfile(String name, PyObject globals, PyObject locals) { execfile_flags(name,globals,locals,Py.getCompilerFlags()); } public static void execfile_flags(String name, PyObject globals, PyObject locals,CompilerFlags cflags) { java.io.FileInputStream file; try { file = new java.io.FileInputStream(name); } catch (java.io.FileNotFoundException e) { throw Py.IOError(e); } PyCode code; try { code = Py.compile_flags(file, name, "exec",cflags); } finally { try { file.close(); } catch (java.io.IOException e) { throw Py.IOError(e); } } Py.runCode(code, locals, globals); } public static void execfile(String name, PyObject globals) { execfile(name, globals, globals); } public static void execfile(String name) { execfile(name, null, null); } public static PyObject filter(PyObject f, PyString s) { if (f == Py.None) return s; PyObject[] args = new PyObject[1]; char[] chars = s.toString().toCharArray(); int i; int j; int n = chars.length; for(i=0, j=0; i 0) n = (stop-start+step-1)/step; else n = (stop-start+step+1)/step; if (n <= 0) return new PyList(); PyObject[] l = new PyObject[n]; int j=start; for (int i=0; i [(seq1[0], seq2[0] ...), (...)]\n"+ "\n"+ "Return a list of tuples, where each tuple contains the i-th element\n"+ "from each of the argument sequences. The returned list is\n"+ "truncated in length to the length of the shortest argument sequence." ); public static PyObject zip(PyObject[] argstar) { int itemsize = argstar.length; if (itemsize < 1) throw Py.TypeError("zip requires at least one sequence"); // Type check the arguments; they must be sequences. Might as well // cache the __iter__() methods. PyObject[] iters = new PyObject[itemsize]; for (int j=0; j < itemsize; j++) { PyObject iter = argstar[j].__iter__(); if (iter == null) { throw Py.TypeError("zip argument #" + (j + 1) + " must support iteration"); } iters[j] = iter; } PyList ret = new PyList(); for (int i=0;; i++) { PyObject[] next = new PyObject[itemsize]; PyInteger index = new PyInteger(i); PyObject item; for (int j=0; j < itemsize; j++) { try { item = iters[j].__iternext__(); } catch (PyException e) { if (Py.matchException(e, Py.StopIteration)) return ret; throw e; } if (item == null) return ret; next[j] = item; } ret.append(new PyTuple(next)); } } public static PyObject __import__(String name) { return __import__(name, null, null, null); } public static PyObject __import__(String name, PyObject globals) { return __import__(name, globals, null, null); } public static PyObject __import__(String name, PyObject globals, PyObject locals) { return __import__(name, globals, locals, null); } public static PyObject __import__(String name, PyObject globals, PyObject locals,PyObject fromlist) { PyFrame frame = Py.getFrame(); if (frame == null) return null; PyObject builtins = frame.f_builtins; if (builtins == null) builtins = Py.getSystemState().builtins; PyObject __import__ = builtins.__finditem__("__import__"); if (__import__ == null) return null; PyObject module = __import__.__call__(new PyObject[] { Py.newString(name), globals, locals, fromlist } ); return module; } private static PyObject[] make_array(PyObject o) { if (o instanceof PyTuple) return ((PyTuple)o).list; PyObject iter = o.__iter__(); // Guess result size and allocate space. int n = 10; try { n = o.__len__(); } catch (PyException exc) { } PyObject[] objs= new PyObject[n]; int i; for (i = 0; ; i++) { PyObject item = iter.__iternext__(); if (item == null) break; if (i >= n) { if (n < 500) { n += 10; } else { n += 100; } PyObject[] newobjs = new PyObject[n]; System.arraycopy(objs, 0, newobjs, 0, objs.length); objs = newobjs; } objs[i] = item; } // Cut back if guess was too large. if (i < n) { PyObject[] newobjs = new PyObject[i]; System.arraycopy(objs, 0, newobjs, 0, i); objs = newobjs; } return objs; } } class ImportFunction extends PyObject { public ImportFunction() {} public PyObject __call__(PyObject args[], String keywords[]) { if (!(args.length < 1 || args[0] instanceof PyString)) throw Py.TypeError("first argument must be a string"); if (keywords.length > 0) throw Py.TypeError("__import__() takes no keyword arguments"); int argc = args.length; String module = args[0].__str__().toString(); PyObject globals = (argc > 1 && args[1] != null) ? args[1] : null; PyObject fromlist = (argc > 3 && args[3] != null) ? args[3] : Py.EmptyTuple; return load(module, globals, fromlist); } private PyObject load(String module, PyObject globals, PyObject fromlist) { PyObject mod = imp.importName(module.intern(), fromlist.__len__() == 0, globals); return mod; } public String toString() { return ""; } }