0001: // Copyright (c) Corporation for National Research Initiatives
0002: package org.python.core;
0003:
0004: import java.util.Hashtable;
0005:
0006: class BuiltinFunctions extends PyBuiltinFunctionSet {
0007:
0008: public BuiltinFunctions(String name, int index, int argcount) {
0009: this (name, index, argcount, argcount);
0010: }
0011:
0012: public BuiltinFunctions(String name, int index, int minargs,
0013: int maxargs) {
0014: super (name, index, minargs, maxargs);
0015: }
0016:
0017: public PyObject __call__() {
0018: switch (this .index) {
0019: case 4:
0020: return __builtin__.globals();
0021: case 16:
0022: return __builtin__.dir();
0023: case 24:
0024: return __builtin__.input();
0025: case 28:
0026: return __builtin__.locals();
0027: case 34:
0028: return Py.newString(__builtin__.raw_input());
0029: case 41:
0030: return __builtin__.vars();
0031: default:
0032: throw info.unexpectedCall(0, false);
0033: }
0034: }
0035:
0036: public PyObject __call__(PyObject arg1) {
0037: switch (this .index) {
0038: case 0:
0039: return Py.newString(__builtin__.chr(Py.py2int(arg1,
0040: "chr(): 1st arg can't be coerced to int")));
0041: case 1:
0042: return Py.newInteger(__builtin__.len(arg1));
0043: case 2:
0044: return __builtin__.range(Py.py2int(arg1,
0045: "range(): 1st arg can't be coerced to int"));
0046: case 3:
0047: return Py.newInteger(__builtin__.ord(Py.py2char(arg1,
0048: "ord(): 1st arg can't be coerced to char")));
0049: case 5:
0050: return __builtin__.hash(arg1);
0051: case 6:
0052: return Py.newUnicode(__builtin__.chr(Py.py2int(arg1,
0053: "unichr(): 1st arg can't be coerced to int")));
0054: case 7:
0055: return __builtin__.abs(arg1);
0056: case 8:
0057: return __builtin__.bool(arg1);
0058: case 11:
0059: return Py.newInteger(__builtin__.id(arg1));
0060: case 12:
0061: return __builtin__.sum(arg1);
0062: case 14:
0063: return Py.newBoolean(__builtin__.callable(arg1));
0064: case 16:
0065: return __builtin__.dir(arg1);
0066: case 18:
0067: return __builtin__.eval(arg1);
0068: case 19:
0069: try {
0070: __builtin__.execfile(arg1.asString(0));
0071: } catch (ConversionException e) {
0072: throw Py
0073: .TypeError("execfile's first argument must be str");
0074: }
0075: return Py.None;
0076: case 23:
0077: return __builtin__.hex(arg1);
0078: case 24:
0079: return __builtin__.input(arg1);
0080: case 25:
0081: return __builtin__.intern(arg1.__str__());
0082: case 27:
0083: return __builtin__.iter(arg1);
0084: case 32:
0085: return __builtin__.oct(arg1);
0086: case 34:
0087: return Py.newString(__builtin__.raw_input(arg1));
0088: case 36:
0089: Object o = arg1.__tojava__(PyModule.class);
0090: if (o == Py.NoConversion) {
0091: o = arg1.__tojava__(PyJavaClass.class);
0092: if (o == Py.NoConversion) {
0093: Py.TypeError("reload() argument must be a module");
0094: }
0095: return __builtin__.reload((PyJavaClass) o);
0096: }
0097: return __builtin__.reload((PyModule) o);
0098: case 37:
0099: return __builtin__.repr(arg1);
0100: case 38:
0101: return __builtin__.round(Py.py2double(arg1));
0102: case 40:
0103: return __builtin__.slice(arg1);
0104: case 41:
0105: return __builtin__.vars(arg1);
0106: case 42:
0107: return __builtin__.xrange(Py.py2int(arg1));
0108: case 30:
0109: return fancyCall(new PyObject[] { arg1 });
0110: case 31:
0111: return fancyCall(new PyObject[] { arg1 });
0112: case 43:
0113: return fancyCall(new PyObject[] { arg1 });
0114: default:
0115: throw info.unexpectedCall(1, false);
0116: }
0117: }
0118:
0119: public PyObject __call__(PyObject arg1, PyObject arg2) {
0120: switch (this .index) {
0121: case 2:
0122: return __builtin__
0123: .range(
0124: Py
0125: .py2int(arg1,
0126: "range(): 1st arg can't be coerced to int"),
0127: Py
0128: .py2int(arg2,
0129: "range(): 2nd arg can't be coerced to int"));
0130: case 6:
0131: return Py.newInteger(__builtin__.cmp(arg1, arg2));
0132: case 9:
0133: return __builtin__.apply(arg1, arg2);
0134: case 10:
0135: return Py.newBoolean(__builtin__.isinstance(arg1, arg2));
0136: case 12:
0137: return __builtin__.sum(arg1, arg2);
0138: case 13:
0139: return __builtin__.coerce(arg1, arg2);
0140: case 15:
0141: __builtin__.delattr(arg1, asString(arg2,
0142: "delattr(): attribute name must be string"));
0143: return Py.None;
0144: case 17:
0145: return __builtin__.divmod(arg1, arg2);
0146: case 18:
0147: return __builtin__.eval(arg1, arg2);
0148: case 19:
0149: try {
0150: __builtin__.execfile(arg1.asString(0), arg2);
0151: } catch (ConversionException e) {
0152: throw Py
0153: .TypeError("execfile's first argument must be str");
0154: }
0155: return Py.None;
0156: case 20:
0157: return __builtin__.filter(arg1, arg2);
0158: case 21:
0159: return __builtin__.getattr(arg1, asString(arg2,
0160: "getattr(): attribute name must be string"));
0161: case 22:
0162: return Py.newBoolean(__builtin__.hasattr(arg1, asString(
0163: arg2, "hasattr(): attribute name must be string")));
0164: case 26:
0165: return Py.newBoolean(__builtin__.issubclass(arg1, arg2));
0166: case 27:
0167: return __builtin__.iter(arg1, arg2);
0168: case 33:
0169: return __builtin__.pow(arg1, arg2);
0170: case 35:
0171: return __builtin__.reduce(arg1, arg2);
0172: case 38:
0173: return __builtin__.round(Py.py2double(arg1), Py
0174: .py2int(arg2));
0175: case 40:
0176: return __builtin__.slice(arg1, arg2);
0177: case 42:
0178: return __builtin__.xrange(Py.py2int(arg1), Py.py2int(arg2));
0179: case 29:
0180: return fancyCall(new PyObject[] { arg1, arg2 });
0181: case 30:
0182: return fancyCall(new PyObject[] { arg1, arg2 });
0183: case 31:
0184: return fancyCall(new PyObject[] { arg1, arg2 });
0185: case 43:
0186: return fancyCall(new PyObject[] { arg1, arg2 });
0187: default:
0188: throw info.unexpectedCall(2, false);
0189: }
0190: }
0191:
0192: public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) {
0193: switch (this .index) {
0194: case 2:
0195: return __builtin__
0196: .range(
0197: Py
0198: .py2int(arg1,
0199: "range(): 1st arg can't be coerced to int"),
0200: Py
0201: .py2int(arg2,
0202: "range(): 2nd arg can't be coerced to int"),
0203: Py
0204: .py2int(arg3,
0205: "range(): 3rd arg can't be coerced to int"));
0206: case 9:
0207: try {
0208: if (arg3 instanceof PyStringMap) {
0209: PyDictionary d = new PyDictionary();
0210: d.update(arg3);
0211: arg3 = d;
0212: }
0213: // this catches both casts of arg3 to a PyDictionary, and
0214: // all casts of keys in the dictionary to PyStrings inside
0215: // apply(PyObject, PyObject, PyDictionary)
0216: PyDictionary d = (PyDictionary) arg3;
0217: return __builtin__.apply(arg1, arg2, d);
0218: } catch (ClassCastException e) {
0219: throw Py.TypeError("apply() 3rd argument must be a "
0220: + "dictionary with string keys");
0221: }
0222: case 18:
0223: return __builtin__.eval(arg1, arg2, arg3);
0224: case 19:
0225: __builtin__.execfile(asString(arg1,
0226: "execfile's first argument must be str", false),
0227: arg2, arg3);
0228: return Py.None;
0229: case 21:
0230: return __builtin__.getattr(arg1, asString(arg2,
0231: "getattr(): attribute name must be string"), arg3);
0232: case 33:
0233: return __builtin__.pow(arg1, arg2, arg3);
0234: case 35:
0235: return __builtin__.reduce(arg1, arg2, arg3);
0236: case 39:
0237: __builtin__.setattr(arg1, asString(arg2,
0238: "setattr(): attribute name must be string"), arg3);
0239: return Py.None;
0240: case 40:
0241: return __builtin__.slice(arg1, arg2, arg3);
0242: case 42:
0243: return __builtin__.xrange(Py.py2int(arg1), Py.py2int(arg2),
0244: Py.py2int(arg3));
0245: case 44:
0246: return fancyCall(new PyObject[] { arg1, arg2, arg3 });
0247: case 29:
0248: return fancyCall(new PyObject[] { arg1, arg2, arg3 });
0249: case 30:
0250: return fancyCall(new PyObject[] { arg1, arg2, arg3 });
0251: case 31:
0252: return fancyCall(new PyObject[] { arg1, arg2, arg3 });
0253: case 43:
0254: return fancyCall(new PyObject[] { arg1, arg2, arg3 });
0255: default:
0256: throw info.unexpectedCall(3, false);
0257: }
0258: }
0259:
0260: /**
0261: * @return arg as an interned String, or throws TypeError with mesage if asString throws a ConversionException
0262: */
0263: private String asString(PyObject arg, String message) {
0264: return asString(arg, message, true);
0265: }
0266:
0267: /**
0268: *
0269: * @param intern - should the resulting string be interned
0270: * @return arg as a String, or throws TypeError with message if asString throws a ConversionException.
0271: */
0272: private String asString(PyObject arg, String message, boolean intern) {
0273:
0274: try {
0275: return intern ? arg.asString(0).intern() : arg.asString(0);
0276: } catch (ConversionException e) {
0277: throw Py.TypeError(message);
0278: }
0279: }
0280:
0281: public PyObject __call__(PyObject arg1, PyObject arg2,
0282: PyObject arg3, PyObject arg4) {
0283: switch (this .index) {
0284: case 44:
0285: return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 });
0286: case 29:
0287: return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 });
0288: case 30:
0289: return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 });
0290: case 31:
0291: return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 });
0292: case 43:
0293: return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 });
0294: default:
0295: throw info.unexpectedCall(4, false);
0296: }
0297: }
0298:
0299: public PyObject fancyCall(PyObject[] args) {
0300: switch (this .index) {
0301: case 44:
0302: if (args.length > 5) {
0303: throw info.unexpectedCall(args.length, false);
0304: }
0305: int flags = 0;
0306: if (args.length > 3) {
0307: flags = Py.py2int(args[3]);
0308: }
0309: boolean dont_inherit = false;
0310: if (args.length > 4) {
0311: dont_inherit = Py.py2boolean(args[4]);
0312: }
0313:
0314: return __builtin__.compile(args[0].toString(), args[1]
0315: .toString(), args[2].toString(), flags,
0316: dont_inherit);
0317: case 29:
0318: return __builtin__.map(args);
0319: case 30:
0320: return __builtin__.max(args);
0321: case 31:
0322: return __builtin__.min(args);
0323: case 43:
0324: return __builtin__.zip(args);
0325: default:
0326: throw info.unexpectedCall(args.length, false);
0327: }
0328: }
0329:
0330: }
0331:
0332: /**
0333: * The builtin module. All builtin functions are defined here
0334: */
0335: public class __builtin__ {
0336: public static void fillWithBuiltins(PyObject dict) {
0337: /* newstyle */
0338: dict.__setitem__("object", PyType.fromClass(PyObject.class));
0339: dict.__setitem__("type", PyType.fromClass(PyType.class));
0340: dict.__setitem__("int", PyType.fromClass(PyInteger.class));
0341: dict.__setitem__("enumerate", PyType
0342: .fromClass(PyEnumerate.class));
0343: dict.__setitem__("float", PyType.fromClass(PyFloat.class));
0344: dict.__setitem__("long", PyType.fromClass(PyLong.class));
0345: dict.__setitem__("complex", PyType.fromClass(PyComplex.class));
0346: dict.__setitem__("dict", PyType.fromClass(PyDictionary.class));
0347: dict.__setitem__("list", PyType.fromClass(PyList.class));
0348: dict.__setitem__("tuple", PyType.fromClass(PyTuple.class));
0349:
0350: dict
0351: .__setitem__("property", PyType
0352: .fromClass(PyProperty.class));
0353: dict.__setitem__("staticmethod", PyType
0354: .fromClass(PyStaticMethod.class));
0355: dict.__setitem__("classmethod", PyType
0356: .fromClass(PyClassMethod.class));
0357: dict.__setitem__("super", PyType.fromClass(PySuper.class));
0358: dict.__setitem__("str", PyType.fromClass(PyString.class));
0359: dict.__setitem__("unicode", PyType.fromClass(PyUnicode.class));
0360: dict.__setitem__("basestring", PyType
0361: .fromClass(PyBaseString.class));
0362: dict.__setitem__("file", PyType.fromClass(PyFile.class));
0363: dict.__setitem__("open", PyType.fromClass(PyFile.class));
0364:
0365: /* - */
0366:
0367: dict.__setitem__("None", Py.None);
0368: dict.__setitem__("NotImplemented", Py.NotImplemented);
0369: dict.__setitem__("Ellipsis", Py.Ellipsis);
0370: dict.__setitem__("True", Py.One);
0371: dict.__setitem__("False", Py.Zero);
0372:
0373: // Work in debug mode by default
0374: // Hopefully add -O option in the future to change this
0375: dict.__setitem__("__debug__", Py.One);
0376:
0377: dict.__setitem__("abs", new BuiltinFunctions("abs", 7, 1));
0378: dict.__setitem__("apply",
0379: new BuiltinFunctions("apply", 9, 2, 3));
0380: dict.__setitem__("bool", new BuiltinFunctions("bool", 8, 1));
0381: dict.__setitem__("callable", new BuiltinFunctions("callable",
0382: 14, 1));
0383: dict.__setitem__("coerce",
0384: new BuiltinFunctions("coerce", 13, 2));
0385: dict.__setitem__("chr", new BuiltinFunctions("chr", 0, 1));
0386: dict.__setitem__("cmp", new BuiltinFunctions("cmp", 6, 2));
0387: dict.__setitem__("globals", new BuiltinFunctions("globals", 4,
0388: 0));
0389: dict.__setitem__("hash", new BuiltinFunctions("hash", 5, 1));
0390: dict.__setitem__("id", new BuiltinFunctions("id", 11, 1));
0391: dict.__setitem__("isinstance", new BuiltinFunctions(
0392: "isinstance", 10, 2));
0393: dict.__setitem__("len", new BuiltinFunctions("len", 1, 1));
0394: dict.__setitem__("ord", new BuiltinFunctions("ord", 3, 1));
0395: dict.__setitem__("range",
0396: new BuiltinFunctions("range", 2, 1, 3));
0397: dict.__setitem__("sum", new BuiltinFunctions("sum", 12, 1, 2));
0398: dict
0399: .__setitem__("unichr", new BuiltinFunctions("unichr",
0400: 6, 1));
0401: dict.__setitem__("compile", new BuiltinFunctions("compile", 44,
0402: 3, -1));
0403: dict.__setitem__("delattr", new BuiltinFunctions("delattr", 15,
0404: 2));
0405: dict.__setitem__("dir", new BuiltinFunctions("dir", 16, 0, 1));
0406: dict.__setitem__("divmod",
0407: new BuiltinFunctions("divmod", 17, 2));
0408: dict
0409: .__setitem__("eval", new BuiltinFunctions("eval", 18,
0410: 1, 3));
0411: dict.__setitem__("execfile", new BuiltinFunctions("execfile",
0412: 19, 1, 3));
0413: dict.__setitem__("filter",
0414: new BuiltinFunctions("filter", 20, 2));
0415: dict.__setitem__("getattr", new BuiltinFunctions("getattr", 21,
0416: 2, 3));
0417: dict.__setitem__("hasattr", new BuiltinFunctions("hasattr", 22,
0418: 2));
0419: dict.__setitem__("hex", new BuiltinFunctions("hex", 23, 1));
0420: dict.__setitem__("input", new BuiltinFunctions("input", 24, 0,
0421: 1));
0422: dict.__setitem__("intern",
0423: new BuiltinFunctions("intern", 25, 1));
0424: dict.__setitem__("issubclass", new BuiltinFunctions(
0425: "issubclass", 26, 2));
0426: dict
0427: .__setitem__("iter", new BuiltinFunctions("iter", 27,
0428: 1, 2));
0429: dict.__setitem__("locals",
0430: new BuiltinFunctions("locals", 28, 0));
0431: dict.__setitem__("map", new BuiltinFunctions("map", 29, 2, -1));
0432: dict.__setitem__("max", new BuiltinFunctions("max", 30, 1, -1));
0433: dict.__setitem__("min", new BuiltinFunctions("min", 31, 1, -1));
0434: dict.__setitem__("oct", new BuiltinFunctions("oct", 32, 1));
0435: dict.__setitem__("pow", new BuiltinFunctions("pow", 33, 2, 3));
0436: dict.__setitem__("raw_input", new BuiltinFunctions("raw_input",
0437: 34, 0, 1));
0438: dict.__setitem__("reduce", new BuiltinFunctions("reduce", 35,
0439: 2, 3));
0440: dict.__setitem__("reload",
0441: new BuiltinFunctions("reload", 36, 1));
0442: dict.__setitem__("repr", new BuiltinFunctions("repr", 37, 1));
0443: dict.__setitem__("round", new BuiltinFunctions("round", 38, 1,
0444: 2));
0445: dict.__setitem__("setattr", new BuiltinFunctions("setattr", 39,
0446: 3));
0447: dict.__setitem__("slice", new BuiltinFunctions("slice", 40, 1,
0448: 3));
0449: dict
0450: .__setitem__("vars", new BuiltinFunctions("vars", 41,
0451: 0, 1));
0452: dict.__setitem__("xrange", new BuiltinFunctions("xrange", 42,
0453: 1, 3));
0454: dict.__setitem__("zip", new BuiltinFunctions("zip", 43, 1, -1));
0455:
0456: dict.__setitem__("__import__", new ImportFunction());
0457:
0458: }
0459:
0460: public static PyObject abs(PyObject o) {
0461: if (o.isNumberType()) {
0462: return o.__abs__();
0463: }
0464: throw Py.TypeError("bad operand type for abs()");
0465: }
0466:
0467: public static PyObject apply(PyObject o, PyObject args) {
0468: return o.__call__(Py.make_array(args));
0469: }
0470:
0471: public static PyObject apply(PyObject o, PyObject args,
0472: PyDictionary kws) {
0473: PyObject[] a;
0474: String[] kw;
0475: Hashtable table = kws.table;
0476: if (table.size() > 0) {
0477: java.util.Enumeration ek = table.keys();
0478: java.util.Enumeration ev = table.elements();
0479: int n = table.size();
0480: kw = new String[n];
0481: PyObject[] aargs = Py.make_array(args);
0482: a = new PyObject[n + aargs.length];
0483: System.arraycopy(aargs, 0, a, 0, aargs.length);
0484: int offset = aargs.length;
0485:
0486: for (int i = 0; i < n; i++) {
0487: kw[i] = ((PyString) ek.nextElement()).internedString();
0488: a[i + offset] = (PyObject) ev.nextElement();
0489: }
0490: return o.__call__(a, kw);
0491: } else {
0492: return apply(o, args);
0493: }
0494: }
0495:
0496: public static PyObject bool(PyObject o) {
0497: return (o == null ? Py.Zero : o.__nonzero__() ? Py.One
0498: : Py.Zero);
0499: }
0500:
0501: public static boolean callable(PyObject o) {
0502: return o.__findattr__("__call__") != null;
0503: }
0504:
0505: public static char unichr(int i) {
0506: return chr(i);
0507: }
0508:
0509: public static char chr(int i) {
0510: if (i < 0 || i > 65535) {
0511: throw Py.ValueError("chr() arg not in range(65535)");
0512: }
0513: return (char) i;
0514: }
0515:
0516: public static int cmp(PyObject x, PyObject y) {
0517: return x._cmp(y);
0518: }
0519:
0520: public static PyTuple coerce(PyObject o1, PyObject o2) {
0521: PyObject[] result = o1._coerce(o2);
0522: if (result != null) {
0523: return new PyTuple(result);
0524: }
0525: throw Py.TypeError("number coercion failed");
0526: }
0527:
0528: public static PyCode compile(String data, String filename,
0529: String type) {
0530: return Py.compile_flags(data, filename, type, Py
0531: .getCompilerFlags());
0532: }
0533:
0534: public static PyCode compile(String data, String filename,
0535: String type, int flags, boolean dont_inherit) {
0536: if ((flags & ~PyTableCode.CO_ALL_FEATURES) != 0) {
0537: throw Py.ValueError("compile(): unrecognised flags");
0538: }
0539: return Py.compile_flags(data, filename, type, Py
0540: .getCompilerFlags(flags, dont_inherit));
0541: }
0542:
0543: public static void delattr(PyObject o, String n) {
0544: o.__delattr__(n);
0545: }
0546:
0547: public static PyObject dir(PyObject o) {
0548: PyList ret = (PyList) o.__dir__();
0549: ret.sort();
0550: return ret;
0551: }
0552:
0553: public static PyObject dir() {
0554: PyObject l = locals();
0555: PyList ret;
0556:
0557: if (l instanceof PyStringMap) {
0558: ret = ((PyStringMap) l).keys();
0559: } else if (l instanceof PyDictionary) {
0560: ret = ((PyDictionary) l).keys();
0561: }
0562:
0563: ret = (PyList) l.invoke("keys");
0564: ret.sort();
0565: return ret;
0566: }
0567:
0568: public static PyObject divmod(PyObject x, PyObject y) {
0569: return x._divmod(y);
0570: }
0571:
0572: public static PyEnumerate enumerate(PyObject seq) {
0573: return new PyEnumerate(seq);
0574: }
0575:
0576: public static PyObject eval(PyObject o, PyObject globals,
0577: PyObject locals) {
0578: PyCode code;
0579: if (o instanceof PyCode) {
0580: code = (PyCode) o;
0581: } else {
0582: if (o instanceof PyString) {
0583: code = compile(o.toString(), "<string>", "eval");
0584: } else {
0585: throw Py
0586: .TypeError("eval: argument 1 must be string or code object");
0587: }
0588: }
0589: return Py.runCode(code, locals, globals);
0590: }
0591:
0592: public static PyObject eval(PyObject o, PyObject globals) {
0593: return eval(o, globals, globals);
0594: }
0595:
0596: public static PyObject eval(PyObject o) {
0597: if (o instanceof PyTableCode && ((PyTableCode) o).hasFreevars()) {
0598: throw Py
0599: .TypeError("code object passed to eval() may not contain free variables");
0600: }
0601: return eval(o, null, null);
0602: }
0603:
0604: public static void execfile(String name, PyObject globals,
0605: PyObject locals) {
0606: execfile_flags(name, globals, locals, Py.getCompilerFlags());
0607: }
0608:
0609: public static void execfile_flags(String name, PyObject globals,
0610: PyObject locals, CompilerFlags cflags) {
0611: java.io.FileInputStream file;
0612: try {
0613: file = new java.io.FileInputStream(name);
0614: } catch (java.io.FileNotFoundException e) {
0615: throw Py.IOError(e);
0616: }
0617: PyCode code;
0618:
0619: try {
0620: code = Py.compile_flags(file, name, "exec", cflags);
0621: } finally {
0622: try {
0623: file.close();
0624: } catch (java.io.IOException e) {
0625: throw Py.IOError(e);
0626: }
0627: }
0628: Py.runCode(code, locals, globals);
0629: }
0630:
0631: public static void execfile(String name, PyObject globals) {
0632: execfile(name, globals, globals);
0633: }
0634:
0635: public static void execfile(String name) {
0636: execfile(name, null, null);
0637: }
0638:
0639: public static PyObject filter(PyObject f, PyString s) {
0640: if (f == Py.None) {
0641: return s;
0642: }
0643: PyObject[] args = new PyObject[1];
0644: char[] chars = s.toString().toCharArray();
0645: int i;
0646: int j;
0647: int n = chars.length;
0648: for (i = 0, j = 0; i < n; i++) {
0649: args[0] = Py.makeCharacter(chars[i]);
0650: if (!f.__call__(args).__nonzero__()) {
0651: continue;
0652: }
0653: chars[j++] = chars[i];
0654: }
0655: return new PyString(new String(chars, 0, j));
0656: }
0657:
0658: public static PyObject filter(PyObject f, PyObject l) {
0659: if (l instanceof PyString) {
0660: return filter(f, (PyString) l);
0661: }
0662: PyList list = new PyList();
0663: PyObject iter = l.__iter__();
0664: for (PyObject item = null; (item = iter.__iternext__()) != null;) {
0665: if (f == Py.None) {
0666: if (!item.__nonzero__()) {
0667: continue;
0668: }
0669: } else if (!f.__call__(item).__nonzero__()) {
0670: continue;
0671: }
0672: list.append(item);
0673: }
0674: if (l instanceof PyTuple) {
0675: return tuple(list);
0676: }
0677: return list;
0678: }
0679:
0680: public static PyObject getattr(PyObject o, String n) {
0681: return o.__getattr__(n);
0682: }
0683:
0684: public static PyObject getattr(PyObject o, String n, PyObject def) {
0685: PyObject val = o.__findattr__(n);
0686: if (val != null) {
0687: return val;
0688: }
0689: return def;
0690: }
0691:
0692: public static PyObject globals() {
0693: return Py.getFrame().f_globals;
0694: }
0695:
0696: public static boolean hasattr(PyObject o, String n) {
0697: try {
0698: return o.__findattr__(n) != null;
0699: } catch (PyException exc) {
0700: if (Py.matchException(exc, Py.AttributeError)) {
0701: return false;
0702: }
0703: throw exc;
0704: }
0705: }
0706:
0707: public static PyInteger hash(PyObject o) {
0708: return o.__hash__();
0709: }
0710:
0711: public static PyString hex(PyObject o) {
0712: try {
0713: return o.__hex__();
0714: } catch (PyException e) {
0715: if (Py.matchException(e, Py.AttributeError))
0716: throw Py
0717: .TypeError("hex() argument can't be converted to hex");
0718: throw e;
0719: }
0720: }
0721:
0722: public static long id(PyObject o) {
0723: return Py.id(o);
0724: }
0725:
0726: public static PyObject input(PyObject prompt) {
0727: String line = raw_input(prompt);
0728: return eval(new PyString(line));
0729: }
0730:
0731: public static PyObject input() {
0732: return input(new PyString(""));
0733: }
0734:
0735: private static PyStringMap internedStrings;
0736:
0737: public static PyString intern(PyString s) {
0738: if (internedStrings == null) {
0739: internedStrings = new PyStringMap();
0740: }
0741:
0742: String istring = s.internedString();
0743: PyObject ret = internedStrings.__finditem__(istring);
0744: if (ret != null) {
0745: return (PyString) ret;
0746: }
0747: if (s instanceof PyStringDerived) {
0748: s = s.__str__();
0749: }
0750: internedStrings.__setitem__(istring, s);
0751: return s;
0752: }
0753:
0754: // xxx find where used, modify with more appropriate if necessary
0755: public static boolean isinstance(PyObject obj, PyObject cls) {
0756: return Py.isInstance(obj, cls);
0757: }
0758:
0759: // xxx find where used, modify with more appropriate if necessary
0760: public static boolean issubclass(PyObject derived, PyObject cls) {
0761: return Py.isSubClass(derived, cls);
0762: }
0763:
0764: public static PyObject iter(PyObject obj) {
0765: return obj.__iter__();
0766: }
0767:
0768: public static PyObject iter(PyObject callable, PyObject sentinel) {
0769: return new PyCallIter(callable, sentinel);
0770: }
0771:
0772: public static int len(PyObject o) {
0773: try {
0774: return o.__len__();
0775: } catch (PyException e) {
0776: // Make this work like CPython where
0777: //
0778: // a = 7; len(a) raises a TypeError,
0779: // a.__len__() raises an AttributeError
0780: // and
0781: // class F: pass
0782: // f = F(); len(f) also raises an AttributeError
0783: //
0784: // Testing the type of o feels unclean though
0785: if (e.type == Py.AttributeError
0786: && !(o instanceof PyInstance)) {
0787: throw Py.TypeError("len() of unsized object");
0788: }
0789: throw e;
0790: }
0791: }
0792:
0793: public static PyObject locals() {
0794: return Py.getFrame().getf_locals();
0795: }
0796:
0797: public static PyObject map(PyObject[] argstar) {
0798: int n = argstar.length - 1;
0799: if (n < 1) {
0800: throw Py.TypeError("map requires at least two arguments");
0801: }
0802: PyObject element;
0803: PyObject f = argstar[0];
0804: PyList list = new PyList();
0805: PyObject[] args = new PyObject[n];
0806: PyObject[] iters = new PyObject[n];
0807:
0808: for (int j = 0; j < n; j++) {
0809: iters[j] = Py.iter(argstar[j + 1], "argument " + (j + 1)
0810: + " to map() must support iteration");
0811: }
0812:
0813: while (true) {
0814: boolean any_items = false;
0815: for (int j = 0; j < n; j++) {
0816: if ((element = iters[j].__iternext__()) != null) {
0817: args[j] = element;
0818: any_items = true;
0819: } else {
0820: args[j] = Py.None;
0821: }
0822: }
0823: if (!any_items) {
0824: break;
0825: }
0826: if (f == Py.None) {
0827: if (n == 1) {
0828: list.append(args[0]);
0829: } else {
0830: list.append(new PyTuple((PyObject[]) args.clone()));
0831: }
0832: } else {
0833: list.append(f.__call__(args));
0834: }
0835: }
0836: return list;
0837: }
0838:
0839: // I've never been happy with max and min builtin's...
0840:
0841: public static PyObject max(PyObject[] l) {
0842: if (l.length == 1) {
0843: return max(l[0]);
0844: }
0845: return max(new PyTuple(l));
0846: }
0847:
0848: private static PyObject max(PyObject o) {
0849: PyObject max = null;
0850: PyObject iter = o.__iter__();
0851: for (PyObject item; (item = iter.__iternext__()) != null;) {
0852: if (max == null || item._gt(max).__nonzero__()) {
0853: max = item;
0854: }
0855: }
0856: if (max == null) {
0857: throw Py.ValueError("max of empty sequence");
0858: }
0859: return max;
0860: }
0861:
0862: public static PyObject min(PyObject[] l) {
0863: if (l.length == 1) {
0864: return min(l[0]);
0865: }
0866: return min(new PyTuple(l));
0867: }
0868:
0869: private static PyObject min(PyObject o) {
0870: PyObject min = null;
0871: PyObject iter = o.__iter__();
0872: for (PyObject item; (item = iter.__iternext__()) != null;) {
0873: if (min == null || item._lt(min).__nonzero__()) {
0874: min = item;
0875: }
0876: }
0877: if (min == null) {
0878: throw Py.ValueError("min of empty sequence");
0879: }
0880: return min;
0881: }
0882:
0883: public static PyString oct(PyObject o) {
0884: return o.__oct__();
0885: }
0886:
0887: public static final int ord(char c) {
0888: return c;
0889: }
0890:
0891: public static PyObject pow(PyObject x, PyObject y) {
0892: return x._pow(y);
0893: }
0894:
0895: private static boolean coerce(PyObject[] objs) {
0896: PyObject x = objs[0];
0897: PyObject y = objs[1];
0898: PyObject[] result;
0899: result = x._coerce(y);
0900: if (result != null) {
0901: objs[0] = result[0];
0902: objs[1] = result[1];
0903: return true;
0904: }
0905: result = y._coerce(x);
0906: if (result != null) {
0907: objs[0] = result[1];
0908: objs[1] = result[0];
0909: return true;
0910: }
0911: return false;
0912: }
0913:
0914: public static PyObject pow(PyObject xi, PyObject yi, PyObject zi) {
0915: PyObject x = xi;
0916: PyObject y = yi;
0917: PyObject z = zi;
0918:
0919: PyObject[] tmp = new PyObject[2];
0920:
0921: tmp[0] = x;
0922: tmp[1] = y;
0923: if (coerce(tmp)) {
0924: x = tmp[0];
0925: y = tmp[1];
0926: tmp[1] = z;
0927: if (coerce(tmp)) {
0928: x = tmp[0];
0929: z = tmp[1];
0930: tmp[0] = y;
0931: if (coerce(tmp)) {
0932: z = tmp[1];
0933: y = tmp[0];
0934: }
0935: }
0936: } else {
0937: tmp[1] = z;
0938: if (coerce(tmp)) {
0939: x = tmp[0];
0940: z = tmp[1];
0941: tmp[0] = y;
0942: if (coerce(tmp)) {
0943: y = tmp[0];
0944: z = tmp[1];
0945: tmp[1] = x;
0946: if (coerce(tmp)) {
0947: x = tmp[1];
0948: y = tmp[0];
0949: }
0950: }
0951: }
0952: }
0953:
0954: if (x.getType() == y.getType() && x.getType() == z.getType()) {
0955: x = x.__pow__(y, z);
0956: if (x != null) {
0957: return x;
0958: }
0959: }
0960: throw Py.TypeError("__pow__ not defined for these operands");
0961: }
0962:
0963: public static PyObject range(int start, int stop, int step) {
0964: if (step == 0) {
0965: throw Py.ValueError("zero step for range()");
0966: }
0967: int n;
0968: if (step > 0) {
0969: n = (stop - start + step - 1) / step;
0970: } else {
0971: n = (stop - start + step + 1) / step;
0972: }
0973: if (n <= 0) {
0974: return new PyList();
0975: }
0976: PyObject[] l = new PyObject[n];
0977: int j = start;
0978: for (int i = 0; i < n; i++) {
0979: l[i] = Py.newInteger(j);
0980: j += step;
0981: }
0982: return new PyList(l);
0983: }
0984:
0985: public static PyObject range(int n) {
0986: return range(0, n, 1);
0987: }
0988:
0989: public static PyObject range(int start, int stop) {
0990: return range(start, stop, 1);
0991: }
0992:
0993: private static PyString readline(PyObject file) {
0994: if (file instanceof PyFile) {
0995: return new PyString(((PyFile) file).readline());
0996: } else {
0997: PyObject ret = file.invoke("readline");
0998: if (!(ret instanceof PyString)) {
0999: throw Py
1000: .TypeError("object.readline() returned non-string");
1001: }
1002: return (PyString) ret;
1003: }
1004: }
1005:
1006: public static String raw_input(PyObject prompt) {
1007: Py.print(prompt);
1008: PyObject stdin = Py.getSystemState().stdin;
1009: String data = readline(stdin).toString();
1010: if (data.endsWith("\n")) {
1011: return data.substring(0, data.length() - 1);
1012: } else {
1013: if (data.length() == 0) {
1014: throw Py.EOFError("raw_input()");
1015: }
1016: }
1017: return data;
1018: }
1019:
1020: public static String raw_input() {
1021: return raw_input(new PyString(""));
1022: }
1023:
1024: public static PyObject reduce(PyObject f, PyObject l, PyObject z) {
1025: PyObject result = z;
1026: PyObject iter = Py.iter(l,
1027: "reduce() arg 2 must support iteration");
1028:
1029: for (PyObject item; (item = iter.__iternext__()) != null;) {
1030: if (result == null) {
1031: result = item;
1032: } else {
1033: result = f.__call__(result, item);
1034: }
1035: }
1036: if (result == null) {
1037: throw Py
1038: .TypeError("reduce of empty sequence with no initial value");
1039: }
1040: return result;
1041: }
1042:
1043: public static PyObject reduce(PyObject f, PyObject l) {
1044: return reduce(f, l, null);
1045: }
1046:
1047: public static PyObject reload(PyModule o) {
1048: return imp.reload(o);
1049: }
1050:
1051: public static PyObject reload(PyJavaClass o) {
1052: return imp.reload(o);
1053: }
1054:
1055: public static PyString repr(PyObject o) {
1056: return o.__repr__();
1057: }
1058:
1059: // This seems awfully special purpose...
1060: public static PyFloat round(double f, int digits) {
1061: boolean neg = f < 0;
1062: double multiple = Math.pow(10., digits);
1063: if (neg) {
1064: f = -f;
1065: }
1066: double tmp = Math.floor(f * multiple + 0.5);
1067: if (neg) {
1068: tmp = -tmp;
1069: }
1070: return new PyFloat(tmp / multiple);
1071: }
1072:
1073: public static PyFloat round(double f) {
1074: return round(f, 0);
1075: }
1076:
1077: public static void setattr(PyObject o, String n, PyObject v) {
1078: o.__setattr__(n, v);
1079: }
1080:
1081: public static PySlice slice(PyObject start, PyObject stop,
1082: PyObject step) {
1083: return new PySlice(start, stop, step);
1084: }
1085:
1086: public static PySlice slice(PyObject start, PyObject stop) {
1087: return slice(start, stop, Py.None);
1088: }
1089:
1090: public static PySlice slice(PyObject stop) {
1091: return slice(Py.None, stop, Py.None);
1092: }
1093:
1094: public static PyObject sum(PyObject seq, PyObject result) {
1095:
1096: if (result instanceof PyString) {
1097: throw Py
1098: .TypeError("sum() can't sum strings [use ''.join(seq) instead]");
1099: }
1100:
1101: PyObject item;
1102: PyObject iter = seq.__iter__();
1103: while ((item = iter.__iternext__()) != null) {
1104: result = result._add(item);
1105: }
1106: return result;
1107: }
1108:
1109: public static PyObject sum(PyObject seq) {
1110: return sum(seq, Py.Zero);
1111: }
1112:
1113: public static PyTuple tuple(PyObject o) {
1114: if (o instanceof PyTuple) {
1115: return (PyTuple) o;
1116: }
1117: if (o instanceof PyList) {
1118: // always make a copy, otherwise the tuple will share the
1119: // underlying data structure with the list object, which
1120: // renders the tuple mutable!
1121: PyList l = (PyList) o;
1122: PyObject[] a = new PyObject[l.size()];
1123: System.arraycopy(l.getArray(), 0, a, 0, a.length);
1124: return new PyTuple(a);
1125: }
1126: return new PyTuple(Py.make_array(o));
1127: }
1128:
1129: public static PyType type(PyObject o) {
1130: return o.getType();
1131: }
1132:
1133: public static PyObject vars(PyObject o) {
1134: try {
1135: return o.__getattr__("__dict__");
1136: } catch (PyException e) {
1137: if (Py.matchException(e, Py.AttributeError))
1138: throw Py
1139: .TypeError("vars() argument must have __dict__ attribute");
1140: throw e;
1141: }
1142: }
1143:
1144: public static PyObject vars() {
1145: return locals();
1146: }
1147:
1148: public static PyObject xrange(int start, int stop, int step) {
1149: return new PyXRange(start, stop, step);
1150: }
1151:
1152: public static PyObject xrange(int n) {
1153: return xrange(0, n, 1);
1154: }
1155:
1156: public static PyObject xrange(int start, int stop) {
1157: return xrange(start, stop, 1);
1158: }
1159:
1160: public static PyString __doc__zip = new PyString(
1161: "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n"
1162: + "\n"
1163: + "Return a list of tuples, where each tuple contains the i-th element\n"
1164: + "from each of the argument sequences. The returned list is\n"
1165: + "truncated in length to the length of the shortest argument sequence.");
1166:
1167: public static PyObject zip(PyObject[] argstar) {
1168: int itemsize = argstar.length;
1169: if (itemsize < 1) {
1170: throw Py.TypeError("zip requires at least one sequence");
1171: }
1172:
1173: // Type check the arguments; they must be sequences. Might as well
1174: // cache the __iter__() methods.
1175: PyObject[] iters = new PyObject[itemsize];
1176:
1177: for (int j = 0; j < itemsize; j++) {
1178: PyObject iter = argstar[j].__iter__();
1179: if (iter == null) {
1180: throw Py.TypeError("zip argument #" + (j + 1)
1181: + " must support iteration");
1182: }
1183: iters[j] = iter;
1184: }
1185:
1186: PyList ret = new PyList();
1187:
1188: for (int i = 0;; i++) {
1189: PyObject[] next = new PyObject[itemsize];
1190: PyObject item;
1191:
1192: for (int j = 0; j < itemsize; j++) {
1193: try {
1194: item = iters[j].__iternext__();
1195: } catch (PyException e) {
1196: if (Py.matchException(e, Py.StopIteration)) {
1197: return ret;
1198: }
1199: throw e;
1200: }
1201: if (item == null) {
1202: return ret;
1203: }
1204: next[j] = item;
1205: }
1206: ret.append(new PyTuple(next));
1207: }
1208: }
1209:
1210: public static PyObject __import__(String name) {
1211: return __import__(name, null, null, null);
1212: }
1213:
1214: public static PyObject __import__(String name, PyObject globals) {
1215: return __import__(name, globals, null, null);
1216: }
1217:
1218: public static PyObject __import__(String name, PyObject globals,
1219: PyObject locals) {
1220: return __import__(name, globals, locals, null);
1221: }
1222:
1223: public static PyObject __import__(String name, PyObject globals,
1224: PyObject locals, PyObject fromlist) {
1225: PyFrame frame = Py.getFrame();
1226: if (frame == null) {
1227: return null;
1228: }
1229: PyObject builtins = frame.f_builtins;
1230: if (builtins == null) {
1231: builtins = Py.getSystemState().builtins;
1232: }
1233:
1234: PyObject __import__ = builtins.__finditem__("__import__");
1235: if (__import__ == null) {
1236: return null;
1237: }
1238:
1239: PyObject module = __import__.__call__(new PyObject[] {
1240: Py.newString(name), globals, locals, fromlist });
1241: return module;
1242: }
1243:
1244: }
1245:
1246: class ImportFunction extends PyObject {
1247: public ImportFunction() {
1248: }
1249:
1250: public PyObject __call__(PyObject args[], String keywords[]) {
1251: if (!(args.length < 1 || args[0] instanceof PyString)) {
1252: throw Py.TypeError("first argument must be a string");
1253: }
1254: if (keywords.length > 0) {
1255: throw Py
1256: .TypeError("__import__() takes no keyword arguments");
1257: }
1258:
1259: int argc = args.length;
1260: String module = args[0].__str__().toString();
1261:
1262: PyObject globals = (argc > 1 && args[1] != null) ? args[1]
1263: : null;
1264: PyObject fromlist = (argc > 3 && args[3] != null) ? args[3]
1265: : Py.EmptyTuple;
1266:
1267: return load(module, globals, fromlist);
1268: }
1269:
1270: private PyObject load(String module, PyObject globals,
1271: PyObject fromlist) {
1272: PyObject mod = imp.importName(module.intern(), fromlist
1273: .__len__() == 0, globals, fromlist);
1274: return mod;
1275: }
1276:
1277: public String toString() {
1278: return "<built-in function __import__>";
1279: }
1280: }
|