Methods.java

package sanskrit;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/** Methods of str, list, dict and tuple (those of set are in {@link PySet}). The receiver is {@code args[0]}. */
final class Methods {
	private Methods() {
	}

	private static final Map<String, Builtin> STR = forStr(strMethods());
	private static final Map<String, Builtin> LIST = listMethods();
	private static final Map<String, Builtin> DICT = dictMethods();
	private static final Map<String, Builtin> TUPLE = tupleMethods();
	private static final Map<String, Builtin> SET = PySet.methods();

	static Builtin lookup(Object o, String name) {
		if (PyStr.is(o))
			return STR.get(name);
		if (o instanceof PyList)
			return LIST.get(name);
		if (o instanceof PyDict)
			return DICT.get(name);
		if (o instanceof PyTuple)
			return TUPLE.get(name);
		if (o instanceof PySet)
			return SET.get(name);
		return null;
	}

	private static void def(Map<String, Builtin> table, String name, Builtin.Fn fn) {
		table.put(name, new Builtin(name, fn));
	}

	private static void defKw(Map<String, Builtin> table, String name, Builtin.Fn fn, Builtin.KwFn kfn) {
		table.put(name, new Builtin(name, fn, kfn));
	}

	/** The methods of str, each one wrapped by {@link #strFn} or {@link #strKwFn}. */
	private static Map<String, Builtin> forStr(Map<String, Builtin> table) {
		for (Map.Entry<String, Builtin> e : table.entrySet()) {
			final Builtin b = e.getValue();
			e.setValue(new Builtin(b.name, strFn(b.fn), b.kwFn == null ? null : strKwFn(b.kwFn)));
		}
		return table;
	}

	/**
	 * A method of str, for a receiver and arguments that are PyStr or String:
	 * the body gets the receiver as it is (see {@link #self}) and the arguments
	 * as Strings, and the result is a PyStr if the receiver is.
	 */
	private static Builtin.Fn strFn(Builtin.Fn fn) {
		return (in, a) -> {
			final boolean obj = a.length > 0 && a[0] instanceof PyStr;
			final Object r = fn.call(in, PyStr.unwrapArgs(a, 1));
			strWork(in, a, r);
			return obj ? PyStr.wrap(r) : r;
		};
	}

	/**
	 * The work of a method of str: it reads the receiver and builds the result.
	 * The strs of a list it returns (split) are new: their memory is counted
	 * here, the one of the result itself is counted by the call.
	 */
	private static void strWork(Interp in, Object[] a, Object r) {
		final long n = a.length > 0 ? PyOps.size(a[0]) : 0;
		in.work(n + PyOps.size(r));
		if (r instanceof PyList)
			in.allocated(n + (long) Memory.OBJECT * ((PyList) r).items.size());
	}

	/** The receiver of a method of str. */
	private static PyStr self(Object[] a) {
		return PyStr.from(a[0]);
	}

	private static Builtin.KwFn strKwFn(Builtin.KwFn fn) {
		return (in, a, kw) -> {
			final boolean obj = a.length > 0 && a[0] instanceof PyStr;
			Map<String, Object> k = kw;
			if (kw != null)
				for (Map.Entry<String, Object> e : kw.entrySet())
					if (e.getValue() instanceof PyStr) {
						k = new java.util.LinkedHashMap<String, Object>(kw);
						for (Map.Entry<String, Object> f : k.entrySet())
							if (f.getValue() instanceof PyStr)
								f.setValue(((PyStr) f.getValue()).s);
						break;
					}
			final Object r = fn.call(in, PyStr.unwrapArgs(a, 1), k);
			strWork(in, a, r);
			return obj ? PyStr.wrap(r) : r;
		};
	}

	/** Checks the number of arguments, not counting the receiver. */
	static void need(Object[] a, int min, int max, String name) {
		int n = a.length - 1;
		if (n < min || n > max) {
			String exp = min == max ? "exactly " + min : max == Integer.MAX_VALUE ? "at least " + min
					: "from " + min + " to " + max;
			throw PyOps.err(Types.TYPE_ERROR, name + "() takes " + exp + " argument" + (max == 1 && min == 1 ? "" : "s")
					+ " (" + n + " given)");
		}
	}

	static void noKw(Map<String, Object> kw, String name, String... allowed) {
		for (String k : kw.keySet()) {
			boolean ok = false;
			for (String s : allowed)
				if (s.equals(k))
					ok = true;
			if (!ok)
				throw PyOps.err(Types.TYPE_ERROR, name + "() got an unexpected keyword argument '" + k + "'");
		}
	}

	private static String str(Object[] a, int i, String method) {
		if (PyStr.is(a[i]) == false)
			throw PyOps.err(Types.TYPE_ERROR, method + "() argument must be str, not " + PyOps.typeName(a[i]));
		return PyStr.text(a[i]);
	}

	static boolean isSpace(int c) {
		return c == 32 || (c >= 9 && c <= 13) || (c >= 28 && c <= 31) || c == 0x85 || c == 0xa0 || c == 0x1680
				|| (c >= 0x2000 && c <= 0x200a) || c == 0x2028 || c == 0x2029 || c == 0x202f || c == 0x205f
				|| c == 0x3000;
	}

	// ------------------------------------------------------------ str

	private static int optIndex(Object[] a, int i, int dflt) {
		if (i >= a.length || a[i] == PyNone.NONE)
			return dflt;
		return PyOps.asIndex(a[i]);
	}

	/** Resolves optional start/end arguments in code points; returns {start, end}. */
	private static int[] window(Object[] a, int first, int len) {
		int start = optIndex(a, first, 0);
		int end = optIndex(a, first + 1, len);
		if (start < 0)
			start = Math.max(0, start + len);
		if (end < 0)
			end = Math.max(0, end + len);
		if (end > len)
			end = len;
		return new int[] { start, end };
	}

	/** Index in code points of sub in s[start:end], or -1. */
	private static int find(PyStr self, String sub, int start, int end, boolean last) {
		final String s = self.s;
		int len = self.length();
		if (start > len)
			return -1;
		if (end < start)
			return -1;
		int so = self.offset(start);
		int eo = self.offset(end);
		int r;
		if (last) {
			r = eo - sub.length() < so ? -1 : s.lastIndexOf(sub, eo - sub.length());
			if (r < so)
				r = -1;
		} else {
			r = s.indexOf(sub, so);
			if (r >= 0 && r + sub.length() > eo)
				r = -1;
		}
		return r < 0 ? -1 : self.cpIndexOf(r);
	}

	private static String stripWith(String s, String chars, boolean left, boolean right) {
		int start = 0, end = s.length();
		if (left) {
			while (start < end) {
				int cp = PyStr.cpAt(s, start);
				if (!(chars == null ? isSpace(cp) : PyStr.containsCp(chars, cp)))
					break;
				start += PyStr.cpSize(cp);
			}
		}
		if (right) {
			while (end > start) {
				int cp = PyStr.cpBefore(s, end);
				if (!(chars == null ? isSpace(cp) : PyStr.containsCp(chars, cp)))
					break;
				end -= PyStr.cpSize(cp);
			}
		}
		return s.substring(start, end);
	}

	private static Builtin.Fn strip(final boolean left, final boolean right, final String name) {
		return (in, a) -> {
			need(a, 0, 1, name);
			String chars = a.length > 1 && a[1] != PyNone.NONE ? str(a, 1, name) : null;
			return stripWith(self(a).s, chars, left, right);
		};
	}

	private static Object split(String s, Object sepArg, int maxsplit, boolean fromRight) {
		PyList out = new PyList();
		if (sepArg == PyNone.NONE) {
			int n = s.length();
			ArrayList<String> parts = new ArrayList<String>();
			if (!fromRight) {
				int i = 0;
				while (true) {
					while (i < n && isSpace(PyStr.cpAt(s, i)))
						i += PyStr.cpSize(PyStr.cpAt(s, i));
					if (i >= n)
						break;
					if (maxsplit >= 0 && parts.size() >= maxsplit) {
						parts.add(s.substring(i));
						break;
					}
					int j = i;
					while (j < n && !isSpace(PyStr.cpAt(s, j)))
						j += PyStr.cpSize(PyStr.cpAt(s, j));
					parts.add(s.substring(i, j));
					Memory.checkParts(parts.size(), s.length());
					i = j;
				}
			} else {
				int i = n;
				ArrayList<String> rev = new ArrayList<String>();
				while (true) {
					while (i > 0 && isSpace(PyStr.cpBefore(s, i)))
						i -= PyStr.cpSize(PyStr.cpBefore(s, i));
					if (i <= 0)
						break;
					if (maxsplit >= 0 && rev.size() >= maxsplit) {
						rev.add(s.substring(0, i));
						break;
					}
					int j = i;
					while (j > 0 && !isSpace(PyStr.cpBefore(s, j)))
						j -= PyStr.cpSize(PyStr.cpBefore(s, j));
					rev.add(s.substring(j, i));
					Memory.checkParts(rev.size(), s.length());
					i = j;
				}
				for (int k = rev.size() - 1; k >= 0; k--)
					parts.add(rev.get(k));
			}
			out.items.addAll(parts);
			return out;
		}
		if (!(sepArg instanceof String))
			throw PyOps.err(Types.TYPE_ERROR, "must be str or None, not " + PyOps.typeName(sepArg));
		String sep = (String) sepArg;
		if (sep.isEmpty())
			throw PyOps.err(Types.VALUE_ERROR, "empty separator");
		if (!fromRight) {
			int i = 0;
			int count = 0;
			while (true) {
				int j = (maxsplit >= 0 && count >= maxsplit) ? -1 : s.indexOf(sep, i);
				if (j < 0) {
					out.items.add(s.substring(i));
					break;
				}
				out.items.add(s.substring(i, j));
				Memory.checkParts(out.items.size(), s.length());
				i = j + sep.length();
				count++;
			}
		} else {
			ArrayList<Object> rev = new ArrayList<Object>();
			int end = s.length();
			int count = 0;
			while (true) {
				int j = (maxsplit >= 0 && count >= maxsplit) ? -1 : (end - sep.length() < 0 ? -1 : s.lastIndexOf(sep, end - sep.length()));
				if (j < 0) {
					rev.add(s.substring(0, end));
					break;
				}
				rev.add(s.substring(j + sep.length(), end));
				Memory.checkParts(rev.size(), s.length());
				end = j;
				count++;
			}
			for (int k = rev.size() - 1; k >= 0; k--)
				out.items.add(rev.get(k));
		}
		return out;
	}

	private static String pad(PyStr self, int width, String fill, int mode) {
		final String s = self.s;
		int len = self.length();
		if (width <= len)
			return s;
		if (PyStr.cpCount(fill) != 1)
			throw PyOps.err(Types.TYPE_ERROR, "The fill character must be exactly one character long");
		if (width > PyOps.MAX_STRING)
			throw PyOps.err(Types.MEMORY_ERROR, "string too large");
		int marg = width - len;
		int left = mode == 0 ? 0 : mode == 1 ? marg : marg / 2 + (marg & width & 1);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < left; i++)
			sb.append(fill);
		sb.append(s);
		for (int i = 0; i < marg - left; i++)
			sb.append(fill);
		return sb.toString();
	}

	private static Builtin.Fn padder(final int mode, final String name) {
		return (in, a) -> {
			need(a, 1, 2, name);
			String fill = a.length > 2 ? str(a, 2, name) : " ";
			return pad(self(a), PyOps.asIndex(a[1]), fill, mode);
		};
	}

	private static Builtin.Fn allChars(final String name, final int kind) {
		return (in, a) -> {
			need(a, 0, 0, name);
			String s = self(a).s;
			if (s.isEmpty())
				return Boolean.FALSE;
			boolean cased = false;
			for (int i = 0; i < s.length();) {
				int cp = PyStr.cpAt(s, i);
				i += PyStr.cpSize(cp);
				switch (kind) {
				case 0:
					if (!Character.isDigit(cp) && !(cp >= 0xb2 && cp <= 0xb3) && cp != 0xb9)
						return Boolean.FALSE;
					break;
				case 1:
					if (!Character.isLetter(cp))
						return Boolean.FALSE;
					break;
				case 2:
					if (!Character.isLetterOrDigit(cp))
						return Boolean.FALSE;
					break;
				case 3:
					if (!isSpace(cp))
						return Boolean.FALSE;
					break;
				case 4:
					if (Character.isLowerCase(cp) || Character.isTitleCase(cp))
						return Boolean.FALSE;
					if (Character.isUpperCase(cp))
						cased = true;
					break;
				default:
					if (Character.isUpperCase(cp) || Character.isTitleCase(cp))
						return Boolean.FALSE;
					if (Character.isLowerCase(cp))
						cased = true;
					break;
				}
			}
			return Boolean.valueOf(kind < 4 || cased);
		};
	}

	private static Object affix(Object[] a, boolean prefix, String name) {
		need(a, 1, 3, name);
		final PyStr self = self(a);
		int len = self.length();
		int[] w = window(a, 2, len);
		if (w[0] > len)
			return Boolean.FALSE;
		String sub = self.s.substring(self.offset(w[0]), self.offset(Math.max(w[0], w[1])));
		Object p = a[1];
		if (p instanceof String)
			return Boolean.valueOf(prefix ? sub.startsWith((String) p) : sub.endsWith((String) p));
		if (p instanceof PyTuple) {
			for (Object o : ((PyTuple) p).items) {
				if (PyStr.is(o) == false)
					throw PyOps.err(Types.TYPE_ERROR, name + " first arg must be str or a tuple of str, not "
							+ PyOps.typeName(o));
				if (prefix ? sub.startsWith(PyStr.text(o)) : sub.endsWith(PyStr.text(o)))
					return Boolean.TRUE;
			}
			return Boolean.FALSE;
		}
		throw PyOps.err(Types.TYPE_ERROR, name + " first arg must be str or a tuple of str, not " + PyOps.typeName(p));
	}

	private static String replace(String s, String old, String rep, int count) {
		if (count < 0)
			count = Integer.MAX_VALUE;
		// the number of replacements, then the length of the result: it is refused before it is built
		int n = 0;
		if (old.isEmpty()) {
			n = (int) Math.min(count, PyStr.cpCount(s) + 1L);
		} else {
			for (int i = s.indexOf(old); i >= 0 && n < count; i = s.indexOf(old, i + old.length()))
				n++;
		}
		if (n == 0)
			return s;
		final long length = s.length() + (long) n * (rep.length() - old.length());
		PyOps.checkString(length);
		StringBuilder sb = new StringBuilder((int) length);
		int i = 0;
		if (old.isEmpty()) {
			// rep goes before each character, and after the last one
			for (; n > 0; n--) {
				sb.append(rep);
				if (i >= s.length())
					break;
				int size = PyStr.cpSize(PyStr.cpAt(s, i));
				sb.append(s, i, i + size);
				i += size;
			}
		} else {
			for (; n > 0; n--) {
				int j = s.indexOf(old, i);
				sb.append(s, i, j).append(rep);
				i = j + old.length();
			}
		}
		return sb.append(s, i, s.length()).toString();
	}

	private static boolean isCased(int cp) {
		return Character.isUpperCase(cp) || Character.isLowerCase(cp) || Character.isTitleCase(cp);
	}

	private static boolean isCaseIgnorable(int cp) {
		switch (Character.getType(cp)) {
		case Character.NON_SPACING_MARK:
		case Character.ENCLOSING_MARK:
		case Character.FORMAT:
		case Character.MODIFIER_LETTER:
		case Character.MODIFIER_SYMBOL:
			return true;
		default:
			return cp == '\'' || cp == '.' || cp == ':' || cp == 0xb7 || cp == 0x2019;
		}
	}

	/** The lower case of the character at i, with the final sigma rule, which looks at the characters around. */
	private static String lowerAt(String s, int i) {
		int cp = PyStr.cpAt(s, i);
		if (cp != 0x3a3)
			return PyStr.ofCp(cp).toLowerCase(Locale.ROOT);
		boolean before = false;
		for (int j = i; j > 0;) {
			int p = PyStr.cpBefore(s, j);
			j -= PyStr.cpSize(p);
			if (isCaseIgnorable(p))
				continue;
			before = isCased(p);
			break;
		}
		boolean after = false;
		for (int j = i + 1; j < s.length();) {
			int q = PyStr.cpAt(s, j);
			j += PyStr.cpSize(q);
			if (isCaseIgnorable(q))
				continue;
			after = isCased(q);
			break;
		}
		return before && !after ? "\u03c2" : "\u03c3";
	}

	/** The title case of a character: the full mapping, whose upper case that changes the length is only capital in its first cased letter. */
	private static String titleOf(int cp) {
		String up = PyStr.ofCp(cp).toUpperCase(Locale.ROOT);
		if (PyStr.cpCount(up) == 1)
			return PyStr.ofCp(Character.toTitleCase(cp));
		StringBuilder sb = new StringBuilder();
		boolean seen = false;
		for (int i = 0; i < up.length();) {
			int c = PyStr.cpAt(up, i);
			i += PyStr.cpSize(c);
			if (seen)
				sb.append(PyStr.ofCp(c).toLowerCase(Locale.ROOT));
			else
				PyStr.appendCp(sb, c);
			if (isCased(c))
				seen = true;
		}
		return sb.toString();
	}

	private static Map<String, Builtin> strMethods() {
		final Map<String, Builtin> table = new HashMap<String, Builtin>();
		def(table, "upper", (in, a) -> {
			need(a, 0, 0, "upper");
			return (self(a).s).toUpperCase(Locale.ROOT);
		});
		def(table, "lower", (in, a) -> {
			need(a, 0, 0, "lower");
			String s = self(a).s;
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < s.length();) {
				sb.append(lowerAt(s, i));
				i += PyStr.cpSize(PyStr.cpAt(s, i));
			}
			return sb.toString();
		});
		def(table, "title", (in, a) -> {
			need(a, 0, 0, "title");
			String s = self(a).s;
			StringBuilder sb = new StringBuilder();
			boolean prev = false;
			for (int i = 0; i < s.length();) {
				int cp = PyStr.cpAt(s, i);
				if (prev)
					sb.append(lowerAt(s, i));
				else
					sb.append(titleOf(cp));
				prev = isCased(cp);
				i += PyStr.cpSize(cp);
			}
			return sb.toString();
		});
		def(table, "capitalize", (in, a) -> {
			need(a, 0, 0, "capitalize");
			String s = self(a).s;
			if (s.isEmpty())
				return s;
			int n = PyStr.cpSize(PyStr.cpAt(s, 0));
			StringBuilder sb = new StringBuilder(titleOf(PyStr.cpAt(s, 0)));
			for (int i = n; i < s.length();) {
				sb.append(lowerAt(s, i));
				i += PyStr.cpSize(PyStr.cpAt(s, i));
			}
			return sb.toString();
		});
		def(table, "swapcase", (in, a) -> {
			need(a, 0, 0, "swapcase");
			String s = self(a).s;
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < s.length();) {
				int cp = PyStr.cpAt(s, i);
				if (Character.isUpperCase(cp))
					sb.append(lowerAt(s, i));
				else if (Character.isLowerCase(cp))
					sb.append(PyStr.ofCp(cp).toUpperCase(Locale.ROOT));
				else
					PyStr.appendCp(sb, cp);
				i += PyStr.cpSize(cp);
			}
			return sb.toString();
		});
		for (final boolean right : new boolean[] { false, true }) {
			final String nm = right ? "rpartition" : "partition";
			def(table, nm, (in, a) -> {
				need(a, 1, 1, nm);
				String s = self(a).s;
				String sep = str(a, 1, nm);
				if (sep.isEmpty())
					throw PyOps.err(Types.VALUE_ERROR, "empty separator");
				int i = right ? s.lastIndexOf(sep) : s.indexOf(sep);
				if (i < 0)
					return new PyTuple(right ? new Object[] { "", "", s } : new Object[] { s, "", "" });
				return new PyTuple(new Object[] { s.substring(0, i), sep, s.substring(i + sep.length()) });
			});
		}
		def(table, "removeprefix", (in, a) -> {
			need(a, 1, 1, "removeprefix");
			String s = self(a).s, p = str(a, 1, "removeprefix");
			return s.startsWith(p) ? s.substring(p.length()) : s;
		});
		def(table, "removesuffix", (in, a) -> {
			need(a, 1, 1, "removesuffix");
			String s = self(a).s, p = str(a, 1, "removesuffix");
			return !p.isEmpty() && s.endsWith(p) ? s.substring(0, s.length() - p.length()) : s;
		});
		def(table, "strip", strip(true, true, "strip"));
		def(table, "lstrip", strip(true, false, "lstrip"));
		def(table, "rstrip", strip(false, true, "rstrip"));
		defKw(table, "split", (in, a) -> {
			need(a, 0, 2, "split");
			return split(self(a).s, a.length > 1 ? a[1] : PyNone.NONE, a.length > 2 ? PyOps.asIndex(a[2]) : -1, false);
		}, (in, a, kw) -> {
			noKw(kw, "split", "sep", "maxsplit");
			Object sep = a.length > 1 ? a[1] : kw.containsKey("sep") ? kw.get("sep") : PyNone.NONE;
			int max = a.length > 2 ? PyOps.asIndex(a[2]) : kw.containsKey("maxsplit") ? PyOps.asIndex(kw.get("maxsplit")) : -1;
			return split(self(a).s, sep, max, false);
		});
		defKw(table, "rsplit", (in, a) -> {
			need(a, 0, 2, "rsplit");
			return split(self(a).s, a.length > 1 ? a[1] : PyNone.NONE, a.length > 2 ? PyOps.asIndex(a[2]) : -1, true);
		}, (in, a, kw) -> {
			noKw(kw, "rsplit", "sep", "maxsplit");
			Object sep = a.length > 1 ? a[1] : kw.containsKey("sep") ? kw.get("sep") : PyNone.NONE;
			int max = a.length > 2 ? PyOps.asIndex(a[2]) : kw.containsKey("maxsplit") ? PyOps.asIndex(kw.get("maxsplit")) : -1;
			return split(self(a).s, sep, max, true);
		});
		def(table, "join", (in, a) -> {
			need(a, 1, 1, "join");
			String sep = self(a).s;
			ArrayList<Object> items = PyOps.toArrayList(a[1]);
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < items.size(); i++) {
				Object o = items.get(i);
				if (PyStr.is(o) == false)
					throw PyOps.err(Types.TYPE_ERROR, "sequence item " + i + ": expected str instance, "
							+ PyOps.typeName(o) + " found");
				PyOps.checkString((long) sb.length() + sep.length() + PyStr.text(o).length());
				if (i > 0)
					sb.append(sep);
				sb.append(PyStr.text(o));
			}
			return sb.toString();
		});
		def(table, "replace", (in, a) -> {
			need(a, 2, 3, "replace");
			return replace(self(a).s, str(a, 1, "replace"), str(a, 2, "replace"),
					a.length > 3 ? PyOps.asIndex(a[3]) : -1);
		});
		for (final String nm : new String[] { "find", "rfind", "index", "rindex" }) {
			final boolean last = nm.startsWith("r");
			final boolean raise = nm.endsWith("index");
			def(table, nm, (in, a) -> {
				need(a, 1, 3, nm);
				PyStr self = self(a);
				int[] w = window(a, 2, self.length());
				int r = find(self, str(a, 1, nm), w[0], w[1], last);
				if (r < 0 && raise)
					throw PyOps.err(Types.VALUE_ERROR, "substring not found");
				return Integer.valueOf(r);
			});
		}
		def(table, "count", (in, a) -> {
			need(a, 1, 3, "count");
			PyStr self = self(a);
			String sub = str(a, 1, "count");
			int len = self.length();
			int[] w = window(a, 2, len);
			if (w[0] > len || w[1] < w[0])
				return Integer.valueOf(0);
			String part = self.s.substring(self.offset(w[0]), self.offset(w[1]));
			if (sub.isEmpty())
				return Integer.valueOf(PyStr.cpCount(part) + 1);
			int n = 0;
			for (int i = part.indexOf(sub); i >= 0; i = part.indexOf(sub, i + sub.length()))
				n++;
			return Integer.valueOf(n);
		});
		def(table, "startswith", (in, a) -> affix(a, true, "startswith"));
		def(table, "endswith", (in, a) -> affix(a, false, "endswith"));
		def(table, "isdigit", allChars("isdigit", 0));
		def(table, "isalpha", allChars("isalpha", 1));
		def(table, "isalnum", allChars("isalnum", 2));
		def(table, "isspace", allChars("isspace", 3));
		def(table, "isupper", allChars("isupper", 4));
		def(table, "islower", allChars("islower", 5));
		def(table, "ljust", padder(0, "ljust"));
		def(table, "rjust", padder(1, "rjust"));
		def(table, "center", padder(2, "center"));
		def(table, "zfill", (in, a) -> {
			need(a, 1, 1, "zfill");
			PyStr self = self(a);
			String s = self.s;
			int width = PyOps.asIndex(a[1]);
			int len = self.length();
			if (width <= len)
				return s;
			if (width > PyOps.MAX_STRING)
				throw PyOps.err(Types.MEMORY_ERROR, "string too large");
			StringBuilder sb = new StringBuilder();
			int start = 0;
			if (!s.isEmpty() && (s.charAt(0) == '+' || s.charAt(0) == '-')) {
				sb.append(s.charAt(0));
				start = 1;
			}
			for (int i = len; i < width; i++)
				sb.append('0');
			sb.append(s, start, s.length());
			return sb.toString();
		});
		defKw(table, "splitlines", (in, a) -> splitlines(self(a).s, a.length > 1 && PyOps.isTrue(a[1])),
				(in, a, kw) -> {
					noKw(kw, "splitlines", "keepends");
					return splitlines(self(a).s, a.length > 1 ? PyOps.isTrue(a[1])
							: kw.containsKey("keepends") && PyOps.isTrue(kw.get("keepends")));
				});
		defKw(table, "format", (in, a) -> Fmt.strFormat(self(a).s, a, 1, null),
				(in, a, kw) -> Fmt.strFormat(self(a).s, a, 1, kw));
		return table;
	}

	private static Object splitlines(String s, boolean keep) {
		PyList out = new PyList();
		int n = s.length();
		int start = 0;
		int i = 0;
		while (i < n) {
			char c = s.charAt(i);
			boolean brk = c == '\n' || c == '\r' || c == 0x0b || c == 0x0c || (c >= 0x1c && c <= 0x1e) || c == 0x85
					|| c == 0x2028 || c == 0x2029;
			if (!brk) {
				i++;
				continue;
			}
			int end = i;
			i++;
			if (c == '\r' && i < n && s.charAt(i) == '\n')
				i++;
			out.items.add(s.substring(start, keep ? i : end));
			Memory.checkParts(out.items.size(), n);
			start = i;
		}
		if (start < n)
			out.items.add(s.substring(start));
		return out;
	}

	// ------------------------------------------------------------ list

	private static Map<String, Builtin> listMethods() {
		final Map<String, Builtin> table = new HashMap<String, Builtin>();
		def(table, "append", (in, a) -> {
			need(a, 1, 1, "append");
			PyOps.checkList(((PyList) a[0]).items.size() + 1L);
			in.allocated(Memory.SLOT);
			((PyList) a[0]).items.add(a[1]);
			return PyNone.NONE;
		});
		def(table, "extend", (in, a) -> {
			need(a, 1, 1, "extend");
			PyOps.extend(in, ((PyList) a[0]).items, a[1]);
			return PyNone.NONE;
		});
		def(table, "insert", (in, a) -> {
			need(a, 2, 2, "insert");
			ArrayList<Object> l = ((PyList) a[0]).items;
			int i = PyOps.asIndex(a[1]);
			if (i < 0)
				i = Math.max(0, i + l.size());
			if (i > l.size())
				i = l.size();
			PyOps.checkList(l.size() + 1L);
			in.work(l.size() - i);
			in.allocated(Memory.SLOT);
			l.add(i, a[2]);
			return PyNone.NONE;
		});
		def(table, "pop", (in, a) -> {
			need(a, 0, 1, "pop");
			ArrayList<Object> l = ((PyList) a[0]).items;
			int i = a.length > 1 ? PyOps.asIndex(a[1]) : -1;
			if (l.isEmpty())
				throw PyOps.err(Types.INDEX_ERROR, "pop from empty list");
			if (i < 0)
				i += l.size();
			if (i < 0 || i >= l.size())
				throw PyOps.err(Types.INDEX_ERROR, "pop index out of range");
			in.work(l.size() - i);
			return l.remove(i);
		});
		def(table, "remove", (in, a) -> {
			need(a, 1, 1, "remove");
			ArrayList<Object> l = ((PyList) a[0]).items;
			in.work(l.size());
			for (int i = 0; i < l.size(); i++)
				if (PyOps.eqItem(l.get(i), a[1])) {
					l.remove(i);
					return PyNone.NONE;
				}
			throw PyOps.err(Types.VALUE_ERROR, "list.remove(x): x not in list");
		});
		def(table, "index", (in, a) -> {
			need(a, 1, 3, "index");
			ArrayList<Object> l = ((PyList) a[0]).items;
			int[] w = window(a, 2, l.size());
			in.work(w[1] - w[0]);
			for (int i = w[0]; i < w[1]; i++)
				if (PyOps.eqItem(l.get(i), a[1]))
					return Integer.valueOf(i);
			throw PyOps.err(Types.VALUE_ERROR, PyOps.repr(a[1]) + " is not in list");
		});
		def(table, "count", (in, a) -> {
			need(a, 1, 1, "count");
			int n = 0;
			in.work(((PyList) a[0]).items.size());
			for (Object o : ((PyList) a[0]).items)
				if (PyOps.eqItem(o, a[1]))
					n++;
			return Integer.valueOf(n);
		});
		defKw(table, "sort", (in, a) -> {
			need(a, 0, 0, "sort");
			PyOps.sortList(((PyList) a[0]).items, in, PyNone.NONE, false);
			return PyNone.NONE;
		}, (in, a, kw) -> {
			need(a, 0, 0, "sort");
			noKw(kw, "sort", "key", "reverse");
			PyOps.sortList(((PyList) a[0]).items, in, kw.containsKey("key") ? kw.get("key") : PyNone.NONE,
					kw.containsKey("reverse") && PyOps.isTrue(kw.get("reverse")));
			return PyNone.NONE;
		});
		def(table, "reverse", (in, a) -> {
			need(a, 0, 0, "reverse");
			in.work(((PyList) a[0]).items.size());
			java.util.Collections.reverse(((PyList) a[0]).items);
			return PyNone.NONE;
		});
		def(table, "clear", (in, a) -> {
			need(a, 0, 0, "clear");
			((PyList) a[0]).items.clear();
			return PyNone.NONE;
		});
		def(table, "copy", (in, a) -> {
			need(a, 0, 0, "copy");
			in.work(((PyList) a[0]).items.size());
			return new PyList(new ArrayList<Object>(((PyList) a[0]).items));
		});
		return table;
	}

	// ------------------------------------------------------------ tuple

	private static Map<String, Builtin> tupleMethods() {
		final Map<String, Builtin> table = new HashMap<String, Builtin>();
		def(table, "index", (in, a) -> {
			need(a, 1, 3, "index");
			Object[] t = ((PyTuple) a[0]).items;
			int[] w = window(a, 2, t.length);
			in.work(w[1] - w[0]);
			for (int i = w[0]; i < w[1]; i++)
				if (PyOps.eqItem(t[i], a[1]))
					return Integer.valueOf(i);
			throw PyOps.err(Types.VALUE_ERROR, "tuple.index(x): x not in tuple");
		});
		def(table, "count", (in, a) -> {
			need(a, 1, 1, "count");
			int n = 0;
			in.work(((PyTuple) a[0]).items.length);
			for (Object o : ((PyTuple) a[0]).items)
				if (PyOps.eqItem(o, a[1]))
					n++;
			return Integer.valueOf(n);
		});
		return table;
	}

	// ------------------------------------------------------------ dict

	static void update(Interp in, PyDict d, Object[] a, Map<String, Object> kw) {
		if (a.length > 2)
			throw PyOps.err(Types.TYPE_ERROR, "update expected at most 1 argument, got " + (a.length - 1));
		if (a.length == 2) {
			Object src = a[1];
			if (src instanceof PyDict) {
				in.work(((PyDict) src).size());
				in.allocated((long) Memory.ENTRY * ((PyDict) src).size());
				for (PyDict.Entry e : new ArrayList<PyDict.Entry>(((PyDict) src).map.values()))
					d.put(e.key, e.value);
			} else {
				int i = 0;
				final ArrayList<Object> items = PyOps.toArrayList(src);
				in.work(items.size());
				in.allocated((long) Memory.ENTRY * items.size());
				for (Object item : items) {
					if (PyOps.isIterable(item) == false)
						throw PyOps.err(Types.TYPE_ERROR, "cannot convert dictionary update sequence element #" + i
								+ " to a sequence");
					ArrayList<Object> pair = PyOps.toArrayList(item);
					if (pair.size() != 2)
						throw PyOps.err(Types.VALUE_ERROR, "dictionary update sequence element #" + i
								+ " has length " + pair.size() + "; 2 is required");
					d.put(pair.get(0), pair.get(1));
					i++;
				}
			}
		}
		if (kw != null)
			for (Map.Entry<String, Object> e : kw.entrySet())
				d.put(e.getKey(), e.getValue());
	}

	private static Map<String, Builtin> dictMethods() {
		final Map<String, Builtin> table = new HashMap<String, Builtin>();
		def(table, "get", (in, a) -> {
			need(a, 1, 2, "get");
			Object v = ((PyDict) a[0]).get(a[1]);
			return v != null ? v : a.length > 2 ? a[2] : PyNone.NONE;
		});
		def(table, "keys", (in, a) -> {
			need(a, 0, 0, "keys");
			return new PyView((PyDict) a[0], PyView.KEYS);
		});
		def(table, "values", (in, a) -> {
			need(a, 0, 0, "values");
			return new PyView((PyDict) a[0], PyView.VALUES);
		});
		def(table, "items", (in, a) -> {
			need(a, 0, 0, "items");
			return new PyView((PyDict) a[0], PyView.ITEMS);
		});
		def(table, "pop", (in, a) -> {
			need(a, 1, 2, "pop");
			Object v = ((PyDict) a[0]).remove(a[1]);
			if (v != null)
				return v;
			if (a.length > 2)
				return a[2];
			throw new PyError(new PyException(Types.KEY_ERROR, new Object[] { a[1] }));
		});
		def(table, "popitem", (in, a) -> {
			need(a, 0, 0, "popitem");
			PyDict d = (PyDict) a[0];
			PyDict.Entry last = null;
			for (PyDict.Entry e : d.map.values())
				last = e;
			if (last == null)
				throw new PyError(new PyException(Types.KEY_ERROR, new Object[] { "popitem(): dictionary is empty" }));
			d.remove(last.key);
			return new PyTuple(new Object[] { last.key, last.value });
		});
		defKw(table, "update", (in, a) -> {
			update(in, (PyDict) a[0], a, null);
			return PyNone.NONE;
		}, (in, a, kw) -> {
			update(in, (PyDict) a[0], a, kw);
			return PyNone.NONE;
		});
		def(table, "setdefault", (in, a) -> {
			need(a, 1, 2, "setdefault");
			PyDict d = (PyDict) a[0];
			Object v = d.get(a[1]);
			if (v != null)
				return v;
			Object dflt = a.length > 2 ? a[2] : PyNone.NONE;
			in.allocated(Memory.ENTRY);
			d.put(a[1], dflt);
			return dflt;
		});
		def(table, "clear", (in, a) -> {
			need(a, 0, 0, "clear");
			((PyDict) a[0]).clear();
			return PyNone.NONE;
		});
		def(table, "copy", (in, a) -> {
			need(a, 0, 0, "copy");
			PyDict r = new PyDict();
			in.work(((PyDict) a[0]).size());
			for (PyDict.Entry e : ((PyDict) a[0]).map.values())
				r.put(e.key, e.value);
			return r;
		});
		return table;
	}
}