Warning : session_start(): open(/var/lib/php/sessions/sess_92nmidqiove5phgkdtik2ebip5, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import java.text.NumberFormat;
class main {
static void test_FactStore() {
PhilosophyBot1 bot = new PhilosophyBot1("\r\n $x weighs $y\r\n => proc {\r\n delete all (last time $x weighed $z)\r\n store (last time $x weighed $y)\r\n }\r\n ");
//bot.printNonMatches = true;
bot.parseProgram();
SimpleFactStore fs = new SimpleFactStore();
fs.verbose = true;
philosophyBot1_factStore(bot, fs, "debug" , true);
bot.addFact("a weighs (50 pounds)");
bot.addFact("b weighs (55 pounds)");
bot.think();
assertEqualsVerbose(ll(
"last time a weighed (50 pounds)",
"last time b weighed (55 pounds)"), sorted(fs.facts()));
bot.addFact("a weighs (52 pounds)");
bot.think();
assertEqualsVerbose(ll(
"last time a weighed (52 pounds)",
"last time b weighed (55 pounds)"), sorted(fs.facts()));
}
static void philosophyBot1_factStore(PhilosophyBot1 bot, IFactStore factStore, Object... __) {
boolean debug = boolPar("debug",__);
bot.addNativePredicate("delete all $x",
(map) -> {
String pat = map.get("$x");
factStore.deleteAll(s -> {
Map map2 = bot.zipIt(pat, s);
if (map2 == null) return false;
if (debug) print("Delete match: " + map2);
return true;
});
return true;
});
bot.addNativePredicate("store $x",
(map) -> {
String x = map.get("$x");
if (debug) print("factStore: store " + x);
factStore.store(x); return true;
});
}
static A assertEqualsVerbose(Object x, A y) {
assertEqualsVerbose((String) null, x, y);
return y;
}
static A assertEqualsVerbose(String msg, Object x, A y) {
if (!eq(x, y)) {
throw fail((msg != null ? msg + ": " : "") + /*sfu*/(y) + " != " + /*sfu*/(x));
} else
print("OK: " + /*sfu*/(x));
return y;
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null) for (A x : a) l.add(x);
return l;
}
static List sorted(Collection c, final Object comparator) {
List l = cloneList(c);
sort(l, makeComparator(comparator));
return l;
}
static List sorted(Collection c) {
List l = cloneList(c);
sort(l);
return l;
}
static boolean boolPar(ThreadLocal tl) {
return boolOptParam(tl);
}
// defaults to false
static boolean boolPar(Object[] __, String name) {
return boolOptParam(__, name);
}
static boolean boolPar(String name, Object[] __) {
return boolOptParam(__, name);
}
static boolean boolPar(String name, Map __) {
return boolOptParam(name, __);
}
static boolean boolPar(String name, Object[] params, boolean defaultValue) {
return optParam(params, name, defaultValue);
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
static boolean print_silent = false; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal print_byThread; // special handling by thread - prefers F1
static volatile Object print_allThreads;
static volatile Object print_preprocess;
static void print() {
print("");
}
static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
// slightly overblown signature to return original object...
static A print(A o) {
ping_okInCleanUp();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null) f = print_allThreads;
if (f != null)
// We do need the general callF machinery here as print_byThread is sometimes shared between modules
if (isFalse(
f instanceof F1 ? ((F1) f).get(s) :
callF(f, s))) return;
print_raw(s);
}
static void print_raw(String s) {
if (print_preprocess != null) s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static void print_autoRotate() {
}
static boolean eq(Object a, Object b) {
return a == b || (a == null ? b == null : b != null && a.equals(b));
}
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static ArrayList cloneList(Collection l) {
if (l == null) return new ArrayList();
synchronized(collectionMutex(l)) {
return new ArrayList (l);
}
}
static void sort(T[] a, Comparator super T> c) {
Arrays.sort(a, c);
}
static void sort(T[] a) {
Arrays.sort(a);
}
static void sort(int[] a) { if (a != null) Arrays.sort(a); }
static void sort(List a, Comparator super T> c) {
Collections.sort(a, c);
}
static void sort(List a) {
Collections.sort(a);
}
static Comparator makeComparator(final Object f) {
if (f instanceof Comparator) return (Comparator) f;
return new Comparator() {
public int compare(Object a, Object b) {
return (Integer) callF(f, a, b);
}
};
}
static boolean boolOptParam(ThreadLocal tl) {
return isTrue(optPar(tl));
}
// defaults to false
static boolean boolOptParam(Object[] __, String name) {
return isTrue(optParam(__, name));
}
static boolean boolOptParam(String name, Object[] __) {
return boolOptParam(__, name);
}
static boolean boolOptParam(String name, Map __) {
return isTrue(optPar(name, __));
}
static A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
static A optParam(ThreadLocal tl) {
return optPar(tl);
}
static Object optParam(String name, Map params) {
return mapGet(params, name);
}
// now also takes a map as single array entry
static A optParam(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
if (!even(l(opt))) throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2)
if (eq(opt[i], name))
return (A) opt[i+1];
return defaultValue;
}
static Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1));
}
static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions )
ping_impl(true);
}
// this syntax should be removed...
static Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static Map> callF_cache = newDangerousWeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static A callF(IF0 f) {
return f == null ? null : f.get();
}
static B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static void callF(VF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Object f, Object... args) { try {
if (f instanceof String)
return callMC((String) f, args);
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1) return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) { throw rethrow(__e); } }
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
makeAccessible(m);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0) return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i+1 < l && s.charAt(i+1) == '\n') ++i;
}
}
return out.toString();
}
static void print_append(Appendable buf, String s, int max) { try {
synchronized(buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) { throw rethrow(__e); } }
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static ArrayList asList(int[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(float[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static ArrayList asList(Iterable s) {
if (s instanceof ArrayList) return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
static Object collectionMutex(List l) {
return l;
}
static Object collectionMutex(Object o) {
if (o instanceof List) return o;
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
if (o instanceof ThreadLocal) // TODO: remove this
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
static A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
static Object optPar(Object[] params, String name) {
return optParam(params, name);
}
static Object optPar(String name, Object[] params) {
return optParam(params, name);
}
static Object optPar(String name, Map params) {
return optParam(name, params);
}
static A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
static A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
static B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
static B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(short[] a) { return a == null ? 0 : a.length; }
static int l(long[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(double[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Iterator i) { return iteratorCount_int_close(i); } // consumes the iterator && closes it if possible
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); }
static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o == null ? 0
: o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: o instanceof Collection ? l((Collection) o)
: o instanceof Object[] ? l((Object[]) o)
: o instanceof boolean[] ? l((boolean[]) o)
: o instanceof byte[] ? l((byte[]) o)
: o instanceof char[] ? l((char[]) o)
: o instanceof short[] ? l((short[]) o)
: o instanceof int[] ? l((int[]) o)
: o instanceof float[] ? l((float[]) o)
: o instanceof double[] ? l((double[]) o)
: o instanceof long[] ? l((long[]) o)
: (Integer) call(o, "size");
}
static int l(IntRange r) { return r == null ? 0 : r.length(); }
static boolean even(int i) {
return (i & 1) == 0;
}
static boolean even(long i) {
return (i & 1) == 0;
}
//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll = false;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions = false;
static Map ping_actions = newWeakHashMap();
static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions ) ping_impl(true /* XXX */);
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized(ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static Object getOpt(String field, Object o) {
return getOpt_cached(o, field);
}
static Object getOpt_raw(Object o, String field) { try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null) return null;
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
// access of static fields is not yet optimized
static Object getOpt(Class c, String field) { try {
if (c == null) return null;
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
makeAccessible(f);
return f.get(null);
} catch (Exception __e) { throw rethrow(__e); } }
static Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static A or(A a, A b) {
return a != null ? a : b;
}
static Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
// initFunction: voidfunc(Map) - is called initially, and after clearing the map
static Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
static HashMap> callMC_cache = new HashMap();
static String callMC_key;
static Method callMC_value;
// varargs assignment fixer for a single string array argument
static Object callMC(String method, String[] arg) {
return callMC(method, new Object[] {arg});
}
static Object callMC(String method, Object... args) { try {
Method me;
if (callMC_cache == null) callMC_cache = new HashMap(); // initializer time workaround
synchronized(callMC_cache) {
me = method == callMC_key ? callMC_value : null;
}
if (me != null) try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
List m;
synchronized(callMC_cache) {
m = callMC_cache.get(method);
}
if (m == null) {
if (callMC_cache.isEmpty()) {
callMC_makeCache();
m = callMC_cache.get(method);
}
if (m == null) throw fail("Method named " + method + " not found in main");
}
int n = m.size();
if (n == 1) {
me = m.get(0);
synchronized(callMC_cache) {
callMC_key = method;
callMC_value = me;
}
try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
}
for (int i = 0; i < n; i++) {
me = m.get(i);
if (call_checkArgs(me, args, false))
return invokeMethod(me, null, args);
}
throw fail("No method called " + method + " with arguments (" + joinWithComma(getClasses(args)) + ") found in main");
} catch (Exception __e) { throw rethrow(__e); } }
static void callMC_makeCache() {
synchronized(callMC_cache) {
callMC_cache.clear();
Class _c = (Class) mc(), c = _c;
while (c != null) {
for (Method m : c.getDeclaredMethods())
if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
makeAccessible(m);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static Object invokeMethod(Method m, Object o, Object... args) { try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) { throw rethrow(__e); } }
static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive()
: isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
static Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
// Note: The error reporting only works with Java VM option --illegal-access=deny
vmBus_send("makeAccessible_error",e, f);
}
return f;
}
static Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error",e, m);
}
return m;
}
static Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error",e, c);
}
return c;
}
static int indexOf(List l, A a, int startIndex) {
if (l == null) return -1;
int n = l(l);
for (int i = startIndex; i < n; i++)
if (eq(l.get(i), a))
return i;
return -1;
}
static int indexOf(List l, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
static int indexOf(List l, A a) {
if (l == null) return -1;
return l.indexOf(a);
}
static int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, char b) {
return a == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, int i, char b) {
return indexOf(a, b, i);
}
static int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(A[] x, A a) {
int n = l(x);
for (int i = 0; i < n; i++)
if (eq(x[i], a))
return i;
return -1;
}
static void rotateStringBuffer(StringBuffer buf, int max) { try {
if (buf == null) return;
synchronized(buf) {
if (buf.length() <= max) return;
try {
int newLength = max/2;
int ofs = buf.length()-newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) { throw rethrow(__e); } }
static void rotateStringBuilder(StringBuilder buf, int max) { try {
if (buf == null) return;
synchronized(buf) {
if (buf.length() <= max) return;
try {
int newLength = max/2;
int ofs = buf.length()-newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) { throw rethrow(__e); } }
static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
static ArrayList emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
// Try to match capacity
static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
// get correct type at once
static ArrayList emptyList(Class c) {
return new ArrayList();
}
static String className(Object o) {
return getClassName(o);
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o == null) return null;
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static Object get_raw(Object o, String field) { try {
if (o == null) return null;
Field f = get_findField(o.getClass(), field);
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
makeAccessible(f);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static Object get(String field, Object o) {
return get(o, field);
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static int iteratorCount_int_close(Iterator i) { try {
int n = 0;
if (i != null) while (i.hasNext()) { i.next(); ++n; }
if (i instanceof AutoCloseable) ((AutoCloseable) i).close();
return n;
} catch (Exception __e) { throw rethrow(__e); } }
static Object call(Object o) {
return callF(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) {
//ret call_cached(o, method, args);
return call_withVarargs(o, method, args);
}
static Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
// TODO: test if android complains about this
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isAWTThread_awt();
}
static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static Thread currentThread() {
return Thread.currentThread();
}
//static final Map> getOpt_cache = newDangerousWeakHashMap(f getOpt_special_init);
static class getOpt_Map extends WeakHashMap {
getOpt_Map() {
if (getOpt_special == null) getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
//print("getOpt clear");
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
//static final Map> getOpt_cache = _registerWeakMap(synchroMap(new getOpt_Map));
static HashMap getOpt_special; // just a marker
/*static void getOpt_special_init(Map map) {
map.put(Class.class, getOpt_special);
map.put(S.class, getOpt_special);
}*/
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
/*if (o instanceof S)
ret getOpt(getBot((S) o), field);*/
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null) return f.get(o);
if (o instanceof DynamicObject)
return mapGet2(((DynamicObject) o).fieldValues, field);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
// used internally - we are in synchronized block
static HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
if (!reflection_classesNotToScan().contains(c.getName())) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
makeAccessible(f);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
}
if (getOpt_cache != null) getOpt_cache.put(c, map);
return map;
}
static Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static List _registerDangerousWeakMap_preList;
static A _registerDangerousWeakMap(A map) {
return _registerDangerousWeakMap(map, null);
}
static A _registerDangerousWeakMap(A map, Object init) {
callF(init, map);
if (init instanceof String) {
final String f = (String) init;
init = new VF1() { public void get(Map map) { try { callMC(f, map) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callMC(f, map)"; }};
}
if (javax() == null) {
// We're in class init
if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList();
_registerDangerousWeakMap_preList.add(pair(map, init));
return map;
}
call(javax(), "_registerDangerousWeakMap", map, init);
return map;
}
static void _onLoad_registerDangerousWeakMap() {
assertNotNull(javax());
if (_registerDangerousWeakMap_preList == null) return;
for (Pair p : _registerDangerousWeakMap_preList)
_registerDangerousWeakMap(p.a, p.b);
_registerDangerousWeakMap_preList = null;
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static List classNames(Collection l) {
return getClassNames(l);
}
static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static String joinWithComma(Collection c) {
return join(", ", c);
}
static String joinWithComma(String... c) {
return join(", ", c);
}
static String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static Class mc() {
return main.class;
}
static void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
static Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static String joinWithSpace(Collection c) {
return join(" ", c);
}
static String joinWithSpace(String... c) {
return join(" ", c);
}
static boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class) return arg instanceof Boolean;
if (type == int.class) return arg instanceof Integer;
if (type == long.class) return arg instanceof Long;
if (type == float.class) return arg instanceof Float;
if (type == short.class) return arg instanceof Short;
if (type == char.class) return arg instanceof Character;
if (type == byte.class) return arg instanceof Byte;
if (type == double.class) return arg instanceof Double;
return type.isInstance(arg);
}
static void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll(vm_busListeners_live(), msg, arg);
pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static Class javax() {
return getJavaX();
}
static int max(int a, int b) { return Math.max(a, b); }
static int max(int a, int b, int c) { return max(max(a, b), c); }
static long max(int a, long b) { return Math.max((long) a, b); }
static long max(long a, long b) { return Math.max(a, b); }
static double max(int a, double b) { return Math.max((double) a, b); }
static float max(float a, float b) { return Math.max(a, b); }
static double max(double a, double b) { return Math.max(a, b); }
static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static double max(double[] c) {
if (c.length == 0) return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static float max(float[] c) {
if (c.length == 0) return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x) x = d;
return x;
}
static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x) x = d;
return x;
}
static Object call_withVarargs(Object o, String method, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
{ if (!(isStaticMethod(m))) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found in " + c);
}
} catch (Exception __e) { throw rethrow(__e); } }
static List _registerWeakMap_preList;
static A _registerWeakMap(A map) {
if (javax() == null) {
// We're in class init
if (_registerWeakMap_preList == null) _registerWeakMap_preList = synchroList();
_registerWeakMap_preList.add(map);
return map;
}
try {
call(javax(), "_registerWeakMap", map);
} catch (Throwable e) {
printException(e);
print("Upgrade JavaX!!");
}
return map;
}
static void _onLoad_registerWeakMap() {
assertNotNull(javax());
if (_registerWeakMap_preList == null) return;
for (Object o : _registerWeakMap_preList)
_registerWeakMap(o);
_registerWeakMap_preList = null;
}
static int isAndroid_flag;
static boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
static Boolean isHeadless_cache;
static boolean isHeadless() {
if (isHeadless_cache != null) return isHeadless_cache;
if (isAndroid()) return isHeadless_cache = true;
if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true;
// Also check if AWT actually works.
// If DISPLAY variable is set but no X server up, this will notice.
try {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) { return isHeadless_cache = true; }
}
static void assertTrue(Object o) {
if (!(eq(o, true) /*|| isTrue(pcallF(o))*/))
throw fail(str(o));
}
static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static volatile boolean licensed_yes = true;
static boolean licensed() {
if (!licensed_yes) return false;
ping_okInCleanUp();
return true;
}
static void licensed_off() {
licensed_yes = false;
}
static void clear(Collection c) {
if (c != null) c.clear();
}
static void put(Map map, A a, B b) {
if (map != null) map.put(a, b);
}
static void put(List l, int i, A a) {
if (l != null && i >= 0 && i < l(l)) l.set(i, a);
}
static B mapGet2(Map map, A a) {
return map == null ? null : map.get(a);
}
static B mapGet2(A a, Map map) {
return map == null ? null : map.get(a);
}
static boolean isSubtypeOf(Class a, Class b) {
return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static Set reflection_classesNotToScan_value = litset(
"jdk.internal.loader.URLClassPath"
);
static Set reflection_classesNotToScan() {
return reflection_classesNotToScan_value;
}
static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
static Pair pair(A a, B b) {
return new Pair(a, b);
}
static Pair pair(A a) {
return new Pair(a, a);
}
static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null) for (Object o : l)
out.add(o == null ? null : getClassName(o));
return out;
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1) return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static String join(Iterable strings) {
return join("", strings);
}
static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static Class _getClass(Object o) {
return o == null ? null
: o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null
: l(args) == 1 ? args[0]
: args;
}
static void pcallFAll(Collection l, Object... args) {
if (l != null) for (Object f : cloneList(l)) pcallF(f, args);
}
static void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static Set vm_busListeners_live_cache;
static Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache; }
static Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static Map vm_busListenersByMessage_live_cache;
static Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache; }
static Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static Class __javax;
static Class getJavaX() { try {
return __javax;
} catch (Exception __e) { throw rethrow(__e); } }
static final Map callOpt_cache = newDangerousWeakHashMap();
static Object callOpt_cached(Object o, String methodName, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
// TODO: (super-rare) case where method exists static and non-static
// with different args
Method me = cache.findMethod(methodName, args);
if (me == null || (me.getModifiers() & Modifier.STATIC) == 0) return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null) return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) { throw rethrow(__e); } }
static _MethodCache callOpt_getCache(Class c) {
synchronized(callOpt_cache) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
}
static boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length-1, nArgs = args.length;
if (nArgs < n) return null;
for (int i = 0; i < n; i++)
if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++)
if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n+1];
arraycopy(args, 0, newArgs, 0, n);
Object[] varArgs = arrayOfType(varArgType, nArgs-n);
arraycopy(args, n, varArgs, 0, nArgs-n);
newArgs[n] = varArgs;
return newArgs;
}
static A printException(A e) {
printStackTrace(e);
return e;
}
static HashSet litset(A... items) {
return lithashset(items);
}
static Object first(Object list) {
return first((Iterable) list);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(IterableIterator i) {
return first((Iterator ) i);
}
static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static Class getClass(Object realm, String name) { try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) { throw rethrow(__e); } }
static String classNameToVM(String name) {
return name.replace(".", "$");
}
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(CharSequence s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
if (o instanceof byte[]) return empty((byte[]) o);
if (o == null) return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(Iterator i) { return i == null || !i.hasNext(); }
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static boolean empty(byte[] a) { return a == null || a.length == 0; }
static boolean empty(short[] a) { return a == null || a.length == 0; }
static boolean empty(File f) { return getFileSize(f) == 0; }
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static A pcallF(F0 f) { try {
return f == null ? null : f.get();
} catch (Throwable __e) { return null; } }
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static void pcallF(VF1 f, A a) {
try {
if (f != null) f.get(a);
} catch (Throwable __e) { _handleException(__e); }
}
static Set vm_generalIdentityHashSet(Object name) {
synchronized(get(javax(), "generalMap")) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = syncIdentityHashSet());
return set;
}
}
static Map vm_generalHashMap(Object name) {
synchronized(get(javax(), "generalMap")) {
Map m = (Map) (vm_generalMap_get(name));
if (m == null)
vm_generalMap_put(name, m = syncHashMap());
return m;
}
}
static boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
static void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, min(a.length, b.length));
}
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
static A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
static A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
static A printStackTrace(A e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace(e));
return e;
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
static String getType(Object o) {
return getClassName(o);
}
static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); }
return null;
}
static volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll("printStackTrace2"));
static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3); // not using pcall here - it could lead to endless loops
}
}
static Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static Map syncHashMap() {
return synchroHashMap();
}
static Throwable printStackTrace2(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace2(e));
return e;
}
static void printStackTrace2() {
printStackTrace2(new Throwable());
}
static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x) x = d;
return x;
}
static A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
static String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static Throwable innerException(Throwable e) {
return getInnerException(e);
}
static Map vm_generalMap_map;
static Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
static B mapPutOrRemove(Map map, A key, B value) {
if (map != null && key != null)
if (value != null) return map.put(key, value);
else return map.remove(key);
return null;
}
static Set synchronizedSet() {
return synchroHashSet();
}
static Set synchronizedSet(Set set) {
return Collections.synchronizedSet(set);
}
static Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
hideCredentials(str(innerException2(e)))) + "\n");
}
// PersistableThrowable doesn't hold GC-disturbing class references in backtrace
static volatile PersistableThrowable lastException_lastException;
static PersistableThrowable lastException() {
return lastException_lastException;
}
static void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }
static String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url))) return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
static Throwable getInnerException(Throwable e) {
if (e == null) return null;
while (e.getCause() != null)
e = e.getCause();
return e;
}
static Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
static Set synchroHashSet() {
return Collections.synchronizedSet(new HashSet ());
}
static Throwable unwrapTrivialExceptionWraps(Throwable e) {
if (e == null) return e;
while (e.getClass() == RuntimeException.class
&& e.getCause() != null && eq(e.getMessage(), str(e.getCause())))
e = e.getCause();
return e;
}
static String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix)) return s;
return replacement + substring(s, l(prefix));
}
static Throwable innerException2(Throwable e) {
if (e == null) return null;
while (empty(e.getMessage()) && e.getCause() != null)
e = e.getCause();
return e;
}
static boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x)) return true; return false;
}
static boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static String hostNameFromURL(String url) { try {
return new URL(url).getHost();
} catch (Exception __e) { throw rethrow(__e); } }
static Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a)) return false;
for (int i = 0; i < listL(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static String substring(String s, int x) {
return substring(s, x, strL(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
if (x >= s.length()) return "";
if (y < x) y = x;
if (y > s.length()) y = s.length();
return s.substring(x, y);
}
static String substring(String s, IntRange r) {
return r == null ? null : substring(s, r.start, r.end);
}
static boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
static String theAGIBlueDomain() {
return "agi.blue";
}
static boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static int strL(String s) {
return s == null ? 0 : s.length();
}
static int listL(Collection l) {
return l == null ? 0 : l.size();
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static boolean eqic(String a, String b) {
if ((a == null) != (b == null)) return false;
if (a == null) return true;
return a.equalsIgnoreCase(b);
}
static boolean eqic(char a, char b) {
if (a == b) return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2) return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static String asString(Object o) {
return o == null ? null : o.toString();
}
static boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la-lb, b, 0, lb);
}
static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static interface IFactStore {
void store(String fact);
void deleteAll(IF1 filter);
}// immutable, has strong refs
final static class _MethodCache {
final Class c;
final HashMap> cache = new HashMap();
_MethodCache(Class c) {
this.c = c; _init(); }
void _init() {
Class _c = c;
while (_c != null) {
for (Method m : _c.getDeclaredMethods())
if (!reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
_c = _c.getSuperclass();
}
// add default methods - this might lead to a duplication
// because the overridden method is also added, but it's not
// a problem except for minimal performance loss.
for (Class intf : allInterfacesImplementedBy(c))
for (Method m : intf.getDeclaredMethods())
if (m.isDefault() && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
}
// Returns only matching methods
Method findMethod(String method, Object[] args) { try {
List m = cache.get(method);
if (m == null) return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) { throw rethrow(__e); } }
Method findStaticMethod(String method, Object[] args) { try {
List m = cache.get(method);
if (m == null) return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (isStaticMethod(me) && call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) { throw rethrow(__e); } }
}static abstract class VF1 implements IVF1 {
public abstract void get(A a);
}static class PersistableThrowable {
String className;
String msg;
String stacktrace;
PersistableThrowable() {}
PersistableThrowable(Throwable e) {
if (e == null)
className = "Crazy Null Error";
else {
className = getClassName(e).replace('/', '.');
msg = e.getMessage();
stacktrace = getStackTrace_noRecord(e);
}
}
public String toString() {
return nempty(msg) ? className + ": " + msg : className;
}
}static class SimpleFactStore implements IFactStore {
List facts = synchroList();
transient boolean verbose = false;
static class Fact extends HasGlobalID {
long created = now();
String text;
Fact() {}
Fact(String text) {
this.text = text;}
public String toString() { return text; }
}
public void store(String fact) {
if (!any(facts, f -> eqic(f.text, fact)))
facts.add(new Fact(fact));
}
public void deleteAll(IF1 filter) {
for (Fact f : cloneList(facts))
if (filter.get(f.text)) {
if (verbose)
print("Deleting fact: " + f);
facts.remove(f);
}
}
List facts() { return map(facts, f -> f.text); }
}static class PhilosophyBot1 {
static class LogicRule implements IFieldsToList {
Object lhs;
Object rhs;
LogicRule() {}
LogicRule(Object lhs, Object rhs) {
this.rhs = rhs;
this.lhs = lhs;}
public String toString() { return "LogicRule(" + lhs + ", " + rhs + ")"; }
public boolean equals(Object o) {
if (!(o instanceof LogicRule)) return false;
LogicRule x = (LogicRule) o;
return eq(lhs, x.lhs) && eq(rhs, x.rhs);
}
public int hashCode() {
int h = 274479962;
h = boostHashCombine(h, _hashCode(lhs));
h = boostHashCombine(h, _hashCode(rhs));
return h;
}
public Object[] _fieldsToList() { return new Object[] {lhs, rhs}; }
}
static class And implements IFieldsToList {
Object a;
Object b;
And() {}
And(Object a, Object b) {
this.b = b;
this.a = a;}
public String toString() { return "And(" + a + ", " + b + ")"; }
public boolean equals(Object o) {
if (!(o instanceof And)) return false;
And x = (And) o;
return eq(a, x.a) && eq(b, x.b);
}
public int hashCode() {
int h = 65975;
h = boostHashCombine(h, _hashCode(a));
h = boostHashCombine(h, _hashCode(b));
return h;
}
public Object[] _fieldsToList() { return new Object[] {a, b}; }
}
static class If implements IFieldsToList {
static String _fieldOrder = "condition thenBlock elseBlock";
Object condition;
Object thenBlock;
Object elseBlock;
If() {}
If(Object condition, Object thenBlock, Object elseBlock) {
this.elseBlock = elseBlock;
this.thenBlock = thenBlock;
this.condition = condition;}
public String toString() { return "If(" + condition + ", " + thenBlock + ", " + elseBlock + ")"; }
public boolean equals(Object o) {
if (!(o instanceof If)) return false;
If x = (If) o;
return eq(condition, x.condition) && eq(thenBlock, x.thenBlock) && eq(elseBlock, x.elseBlock);
}
public int hashCode() {
int h = 2365;
h = boostHashCombine(h, _hashCode(condition));
h = boostHashCombine(h, _hashCode(thenBlock));
h = boostHashCombine(h, _hashCode(elseBlock));
return h;
}
public Object[] _fieldsToList() { return new Object[] {condition, thenBlock, elseBlock}; }
}
static class For implements IFieldsToList {
static String _fieldOrder = "var condition body";
Object var;
Object condition;
Object body;
For() {}
For(Object var, Object condition, Object body) {
this.body = body;
this.condition = condition;
this.var = var;}
public String toString() { return "For(" + var + ", " + condition + ", " + body + ")"; }
public boolean equals(Object o) {
if (!(o instanceof For)) return false;
For x = (For) o;
return eq(var, x.var) && eq(condition, x.condition) && eq(body, x.body);
}
public int hashCode() {
int h = 70825;
h = boostHashCombine(h, _hashCode(var));
h = boostHashCombine(h, _hashCode(condition));
h = boostHashCombine(h, _hashCode(body));
return h;
}
public Object[] _fieldsToList() { return new Object[] {var, condition, body}; }
}
static class While implements IFieldsToList {
static String _fieldOrder = "condition body";
Object condition;
Object body;
While() {}
While(Object condition, Object body) {
this.body = body;
this.condition = condition;}
public String toString() { return "While(" + condition + ", " + body + ")"; }
public boolean equals(Object o) {
if (!(o instanceof While)) return false;
While x = (While) o;
return eq(condition, x.condition) && eq(body, x.body);
}
public int hashCode() {
int h = 83548945;
h = boostHashCombine(h, _hashCode(condition));
h = boostHashCombine(h, _hashCode(body));
return h;
}
public Object[] _fieldsToList() { return new Object[] {condition, body}; }
}
// native predicate return type (Bool/SS/null)
// like a native predicate, but doesn't return anything
static class CodeFragment implements IFieldsToList {
static String _fieldOrder = "head body keepBrackets";
String head;
IVF2, Env> body;
boolean keepBrackets = false;
CodeFragment() {}
CodeFragment(String head, IVF2, Env> body, boolean keepBrackets) {
this.keepBrackets = keepBrackets;
this.body = body;
this.head = head;}
public String toString() { return "CodeFragment(" + head + ", " + body + ", " + keepBrackets + ")"; }
public boolean equals(Object o) {
if (!(o instanceof CodeFragment)) return false;
CodeFragment x = (CodeFragment) o;
return eq(head, x.head) && eq(body, x.body) && eq(keepBrackets, x.keepBrackets);
}
public int hashCode() {
int h = 534055805;
h = boostHashCombine(h, _hashCode(head));
h = boostHashCombine(h, _hashCode(body));
h = boostHashCombine(h, _hashCode(keepBrackets));
return h;
}
public Object[] _fieldsToList() { return new Object[] {head, body, keepBrackets}; }
CodeFragment(String head, IVF2, Env> body) { this.head = head; this.body = body; }
}
static class Env {
boolean wantAlternatives = false;
boolean wantAlternatives() { return wantAlternatives; }
}
static class WithAlternative implements IFieldsToList {
IF0 alternative;
Object result;
WithAlternative() {}
WithAlternative(IF0 alternative, Object result) {
this.result = result;
this.alternative = alternative;}
public String toString() { return "WithAlternative(" + alternative + ", " + result + ")"; }
public boolean equals(Object o) {
if (!(o instanceof WithAlternative)) return false;
WithAlternative x = (WithAlternative) o;
return eq(alternative, x.alternative) && eq(result, x.result);
}
public int hashCode() {
int h = -1195262233;
h = boostHashCombine(h, _hashCode(alternative));
h = boostHashCombine(h, _hashCode(result));
return h;
}
public Object[] _fieldsToList() { return new Object[] {alternative, result}; }
}
// body takes variable mapping
// body can return
// Bool => immediate result (ok or fail)
// SS => variable mapping
// WithAlternative
// null => not applicable
static class NativePredicate implements IFieldsToList {
static String _fieldOrder = "head body";
String head;
IF2, Env, Object> body;
NativePredicate() {}
NativePredicate(String head, IF2, Env, Object> body) {
this.body = body;
this.head = head;}
public String toString() { return "NativePredicate(" + head + ", " + body + ")"; }
public boolean equals(Object o) {
if (!(o instanceof NativePredicate)) return false;
NativePredicate x = (NativePredicate) o;
return eq(head, x.head) && eq(body, x.body);
}
public int hashCode() {
int h = 1520196416;
h = boostHashCombine(h, _hashCode(head));
h = boostHashCombine(h, _hashCode(body));
return h;
}
public Object[] _fieldsToList() { return new Object[] {head, body}; }
}
// procedures are a list of statements
transient String program;
transient int maxRounds = 1000;
transient Set facts = linkedCISet();
transient Set originalFacts;
transient LinkedHashSet logicRules = new LinkedHashSet();
transient AllOnAll rulesOnFacts = new AllOnAll();
transient AllOnAll codeOnFacts = new AllOnAll();
transient AllOnAll, String> anyCodeOnFacts = new AllOnAll();
transient List proceduresToRun = new ArrayList();
// parsed procedures
transient long proceduresExecuted;
transient List nativePredicates = new ArrayList();
transient boolean debugNativeCalls = true, debugAllCmds = true;
transient List onProcedureEnded = new ArrayList();
transient boolean printNonMatches, debugContradictionChecks;
transient boolean standardImportsLoaded = false;
transient Set vars = litciset("x", "y", "z");
PhilosophyBot1() {
// find contradictions
anyCodeOnFacts.newA(fact -> {
Boolean b = checkNativeCondition(fact);
if (debugContradictionChecks)
print("Fact check: " + b + " - " + fact);
if (isFalse(b))
addFact("contradiction");
});
}
PhilosophyBot1(String program) { this();
this.program = program; }
void addLogicRule(LogicRule rule) {
if (logicRules.add(rule)) {
print("Got logic rule", rule);
rulesOnFacts.newA(rule); // to combine it with the facts
}
}
void addFact(String fact) {
fact = trim(fact);
if (empty(fact)) return;
fact = tok_deRoundBracket(fact);
// Check if it's a procedure
List tok = javaTokWithBrackets(fact);
if (countCodeTokens(tok) == 2 && firstTokenEqic(tok, "proc")
&& isCurlyBracketed(getCodeToken(tok, 1))) { try {
// It's a procedure!
String proc = uncurly_keepSpaces(getCodeToken(tok, 1));
if (proceduresToRun.add(parseProcedure(proc))) {
print("Got procedure:");
print(indentx("> ", proc));
}
} catch (Throwable __e) { _handleException(__e); }} /*else if (countCodeTokens(tok) == 2 && firstTokenEqic(tok, "java")
&& isCurlyBracketed(getCodeToken(tok, 1))) pcall {
// It's Java code
}*/ else // It's a fact, not a procedure
if (facts.add(fact)) {
print("Got fact: " + fact);
rulesOnFacts.newB(fact); // to combine it with the rules
codeOnFacts.newB(fact);
anyCodeOnFacts.newB(fact);
}
}
void addFacts_possibleAnd(Object o) {
if (o instanceof And) {
Object a = ((And) o).a;
Object b = ((And) o).b;
addFacts_possibleAnd(a);
addFacts_possibleAnd(b);
} else if (o != null)
addFact((String) o);
}
void runProcedure(String proc) { try {
print("Running procedure.");
runParsedProcedure(parseProcedure(proc));
} catch (Throwable __e) { _handleException(__e); }}
void runParsedProcedure(List commands) {
runParsedProcedure(commands, proceduresToRun);
}
void runParsedProcedure(List commands, List whereToPostCode) {
++proceduresExecuted;
Env env = new Env();
List remainingCommands = cloneLinkedList(commands);
Object cmd;
while ((cmd = popFirst(remainingCommands)) != null) {
if (cmd instanceof List) { runParsedProcedure(((List) cmd)); continue; }
if (debugAllCmds)
print("Running cmd: " + sfu(cmd));
if (cmd instanceof If) {
Object condition = ((If) cmd).condition;
Object thenBlock = ((If) cmd).thenBlock;
Object elseBlock = ((If) cmd).elseBlock;
Object blockToRun = checkCondition(condition) ? thenBlock : elseBlock;
runParsedProcedure(ll(blockToRun));
} else if (cmd instanceof For) {
Object var = ((For) cmd).var;
Object condition = ((For) cmd).condition;
Object body = ((For) cmd).body;
// make a new logic rule and add it
// assume the variable is globally declared as a variable
addLogicRule(new LogicRule(condition, "proc {\n" + body + "\n}"));
} else if (cmd instanceof While) {
Object condition = ((While) cmd).condition;
Object body = ((While) cmd).body;
boolean b = checkCondition(condition);
if (!b) return;
whereToPostCode.add(ll(body, cmd));
} else if (cmd instanceof String) {
Object result = runNativePredicate(((String) cmd), env);
if (result != null) {
result = unpackWithAlternativeOrIterator(result);
if (isFalse(result)) return;
if (isTrueOpt(result)) continue;
Map mapping = (Map) result; // assume it's a variable mapping
// apply to all remaining commands and continue
List remainingCommands2 = mapToLinkedList(remainingCommands,
c -> replaceVars(c, mapValues("optRound",mapping)));
print("Applying var mapping " + mapping + " to " + remainingCommands
+ " => " + remainingCommands2);
remainingCommands = remainingCommands2;
} else
addFact(((String) cmd));
} else if (cmd != null)
throw fail("Unimplemented command: " + cmd);
}
pcallFAll(onProcedureEnded, commands); // notify listeners
}
// return var mapping (SS), Bool or null for no matching predicate
Object runNativePredicate(String s, Env env) {
for (NativePredicate np : nativePredicates) {
Map map = zipIt(np.head, s);
if (map != null) {
Object result = np.body.get(mapValues("tok_deRoundBracket",map), env);
if (debugNativeCalls)
print("Native predicate result: " + np.head + " => " + result);
if (result instanceof Map && nempty(map)) {
result = mapKeys((Map) result, var -> lookupOrKeep(map, var));
if (debugNativeCalls)
print("Rewrote native predicate result: " + result);
}
{ Object __17= result; if (__17 != null) return __17; }
} else
if (printNonMatches)
print("Non-match: " + quote(np.head) + " / " + quote(s));
}
return null;
}
// returns false if unknown
boolean checkCondition(Object o) {
return isTrue(checkConditionOpt(o));
}
// returns null if unknown
Boolean checkConditionOpt(Object o) {
if (o instanceof String) {
if (contains(facts, ((String) o))) return true;
{ Boolean b = checkNativeCondition(((String) o)); if (b != null) return b; }
}
print("Ignoring condition: " + o);
return null;
}
Boolean checkNativeCondition(String o) {
Object result = runNativePredicate(o, nu(Env.class, "wantAlternatives" , false));
result = unpackWithAlternativeOrIterator(result);
if (result instanceof Boolean) return ((Boolean) result);
if (result instanceof Map) return true; // TODO
return null;
}
List parsePythonesqueProcedure(String proc) {
//printStruct(proc);
proc = withoutLinesEmptyAfterTrim(proc);
//printStruct(proc);
proc = autoUnindent(proc);
//printStruct(proc);
//print(indentx("> ", proc));
List l = groupPythonStyleIndents_honoringBrackets(proc);
//pnl("unpythonized ", l);
List out = new ArrayList();
If lastIf = null;
for (int i = 0; i < l(l); i++) {
String s = l.get(i);
List tok = javaTokWithBrackets(s);
if (eqic(firstCodeToken(tok), "if")) {
assertEquals(s, ":", getCodeToken(tok, 2));
out.add(lastIf = new If(deRoundBracket(getCodeToken(tok, 1)),
parsePythonesqueProcedure(joinSubList(tok, 3*2)), null));
continue;
}
if (eqic(firstCodeToken(tok), "while")) {
assertEquals(s, ":", getCodeToken(tok, 2));
out.add(new While(deRoundBracket(getCodeToken(tok, 1)),
parsePythonesqueProcedure(joinSubList(tok, 3*2))));
continue;
}
if (eqic(firstCodeToken(tok), "else") && eqic(secondCodeToken(tok), "if")) {
Object last = last(out);
if (lastIf == null) throw fail("Else if without if");
assertEquals(s, ":", getCodeToken(tok, 3));
lastIf.elseBlock = lastIf = new If(deRoundBracket(getCodeToken(tok, 2)),
parsePythonesqueProcedure(joinSubList(tok, 4*2)), null);
continue;
}
if (eqic(firstCodeToken(tok), "else")) {
Object last = last(out);
if (lastIf == null) throw fail("Else without if");
assertEquals(s, ":", getCodeToken(tok, 1));
lastIf.elseBlock = joinSubList(tok, 2*2);
continue;
}
lastIf = null;
if (eqic(firstCodeToken(tok), "for")) {
assertEquals(s, ":", getCodeToken(tok, 2));
String cond = getCodeToken(tok, 1);
// cond looks like: "(y | x has a y)"
cond = deRoundBracket(cond);
List tok2 = javaTok(cond);
assertEquals(cond, "|", getCodeToken(tok2, 1));
String var = assertIdentifier(cond, getCodeToken(tok2, 0));
String actualCondition = trimJoinSubList(tok2, 2*2+1);
out.add(new For(var, actualCondition, parsePythonesqueProcedure(joinSubList(tok, 3*2))));
} else
out.add(s);
}
//pnl("Parsed procedure ", out);
return out;
}
List parseProcedure(String s) {
return parsePythonesqueProcedure(s);
}
Object splitAtAmpersand2(String s) {
List l = tok_splitAtAmpersand(s);
if (l(l) == 1) return s;
return new And(first(l), splitAtAmpersand2(join(" & ", dropFirst(l))));
}
// "zip" a condition with a fact (match word-by-word)
Map zipIt(String cond, String fact) {
Map map = zipIt_keepBrackets(cond, fact);
if (map == null) return null; // no match
return mapValues("tok_deRoundOrCurlyBracket",map);
}
// "zip" a condition with a fact (match word-by-word)
Map zipIt_keepBrackets(String cond, String fact) {
Map map = gazelle_deepZip_keepBrackets(cond, fact);
if (map == null) return null; // no match
if (!all(keys(map), s -> isVar(s))) return null; /*with print("Non-variable changes, exiting")*/;
return map;
}
boolean isVar(String s) {
return s != null &&
(vars.contains(s) || s.startsWith("var_") || isDollarVar(s));
}
Object replaceVars(Object o, Map map) {
if (empty(map)) return o;
// XXX: recurse through all structures
if (o instanceof And) {
Object a = ((And) o).a;
Object b = ((And) o).b; return new And(replaceVars(a, map), replaceVars(b, map)); }
if (o instanceof If) {
Object condition = ((If) o).condition;
Object thenBlock = ((If) o).thenBlock;
Object elseBlock = ((If) o).elseBlock; return new If(replaceVars(condition, map), replaceVars(thenBlock, map), replaceVars(elseBlock, map)); }
if (o instanceof For && ((For) o).var instanceof String) {
String var = (String) (((For) o).var);
Object condition = ((For) o).condition;
Object body = ((For) o).body; return new For(replaceVars(var, map), replaceVars(condition, map), replaceVars(body, map)); }
if (o instanceof LogicRule) {
Object lhs = ((LogicRule) o).lhs;
Object rhs = ((LogicRule) o).rhs; return new LogicRule(replaceVars(lhs, map), replaceVars(rhs, map)); }
return join(replaceCodeTokensUsingMap(javaTok((String) o), map));
}
void applyLogicRuleToFact(LogicRule rule, String fact) {
Object lhs = rule.lhs, rhs = rule.rhs;
Object cond, remaining = null;
if (lhs instanceof And) {
Object a = ((And) lhs).a;
Object b = ((And) lhs).b;
cond = a;
remaining = b;
} else
cond = lhs;
// now we match the condition with the fact
Map map = zipIt_keepBrackets((String) cond, fact);
if (map == null) {
if (printNonMatches)
print("Non-match: " + quote(cond) + " / " + quote(fact));
return; // no match
}
// Now we have a proper mapping with the keys being variables!
print("Match: " + quote(cond) + " / " + quote(fact));
// drop round brackets
// XXX? map = mapValues tok_deRoundBracket(map);
// Apply mapping to right hand side
Object rhs_replaced = replaceVars(rhs, map);
print("rhs_replaced", rhs_replaced);
if (remaining == null) {
// Add as fact
addFacts_possibleAnd(rhs_replaced);
} else {
// Apply mapping to remaining condition
Object remaining_replaced = replaceVars(remaining, map);
addLogicRule(new LogicRule(remaining_replaced, rhs_replaced));
}
}
public void run() {
parseProgram();
think();
}
boolean smartParser1_verbose = false;
void smartParser1(String program) {
// split into paragraphs and unindent
List paragraphs = map(s -> withoutLeadingLinesEmptyAfterTrim_autoUnindent(rtrim(s)), tok_splitAtEmptyLines(program));
if (smartParser1_verbose) print("Got " + n2(paragraphs, "parapraph"));
// print the parapraphs
if (smartParser1_verbose) print(joinWithEmptyLines(map(s -> indentx("> ", s), paragraphs)));
// throw away comment-only and quoted paragraphs (assume it's a title)
List paragraphs2 = antiFilter(paragraphs, s ->
isSingleLine(trim(s)) && isQuoted(trim(s)) || countJavaTokens(s) == 0
|| endsWith(rtrim(s), "----"));
if (smartParser1_verbose) print("Got " + n2(paragraphs2, "filtered paragraph"));
if (smartParser1_verbose) print(joinWithEmptyLines(map(s -> indentx("> ", s), paragraphs2)));
// find fact paragraphs
if (smartParser1_verbose) print(map("allLinesAreUnindented",paragraphs2));
Pair, List> p1 = filterAntiFilter(s ->
!isSingleLine(trim(s)) && allLinesAreUnindented(s), paragraphs2);
List multiFactParagraphs = p1.a, paragraphs3 = p1.b;
for (String para : multiFactParagraphs)
for (String s : tlft(para))
addFact(s);
// find logic rules
List paragraphs4 = new ArrayList();
for (String para : paragraphs3) {
Pair p = splitAtDoubleArrow_pair(para);
if (p == null) { paragraphs4.add(para); continue; }
addLogicRule(new LogicRule(splitAtAmpersand2(p.a), splitAtAmpersand2(p.b)));
}
if (smartParser1_verbose) pnlStruct("Unparsed - assuming facts", paragraphs4);
// assume the unparsed stuff consists of facts
for (String para : paragraphs4)
addFact(para);
originalFacts = cloneCISet(facts);
}
void parseProgram() {
loadProgram(program);
}
void loadProgram(String program) {
smartParser1(program);
}
boolean doSomeLogic() {
boolean anyAction = false;
Pair p;
while ((p = rulesOnFacts.next()) != null) {
anyAction = true;
//print("Combination: " + p);
applyLogicRuleToFact(p.a, p.b);
}
Pair p2;
while ((p2 = codeOnFacts.next()) != null) {
anyAction = true;
//print("Combination: " + p2);
applyCodeFragmentToFact(p2.a, p2.b);
}
Pair, String> p3;
while ((p3 = anyCodeOnFacts.next()) != null) {
anyAction = true;
//print("Combination: " + p3);
pcallF(p3.a, p3.b);
}
return anyAction;
}
void applyCodeFragmentToFact(CodeFragment cf, String fact) {
Map map = cf.keepBrackets ? zipIt_keepBrackets(cf.head, fact) : zipIt(cf.head, fact);
if (map != null)
cf.body.get(mapValues("tok_deRoundBracket",map), new Env());
}
// indicator for end of thought process (when this stays stable)
long size() {
return l(logicRules) + l(facts) + proceduresExecuted;
}
void think() {
int round = 0;
while (round++ < maxRounds) {
long lastSize = size();
print("Logic round " + round + ", size: " + lastSize);
while (doSomeLogic() && round++ < maxRounds) {}
for (List proc : getAndClearList(proceduresToRun))
runParsedProcedure(proc);
if (size() == lastSize) {
print("No changes, exiting");
break;
}
}
// We're done logicking, so print all the facts gathered
List factsToPrint = listMinusList(facts, originalFacts);
pnlWithHeading("Facts I deduced", factsToPrint);
// Print the actual output
List output = new ArrayList();
for (String fact : factsToPrint) {
List tok = javaTokWithBrackets(fact);
if (countCodeTokens(tok) == 2 && eqic(getCodeToken(tok, 0), "print"))
// For the user, we print without all the round brackets
output.add(tok_dropRoundBrackets(getCodeToken(tok, 1)));
}
pnlWithHeading("Bot Output", output);
}
void addNativePredicate(String head, IF0 body) {
nativePredicates.add(new NativePredicate(head, (map, env) -> body.get()));
}
void addNativePredicate(String head, IF1, Object> body) {
nativePredicates.add(new NativePredicate(head, (map, env) -> body.get(map)));
}
void addNativePredicate(String head, IF2, Env, Object> body) {
nativePredicates.add(new NativePredicate(head, body));
}
// when you only need one result
Object unpackWithAlternativeOrIterator(Object result) {
if (result instanceof Iterator) return first((Iterator) result);
if (result instanceof WithAlternative) return ((WithAlternative) result).result;
return result;
}
void onFactDo(String head, IVF2, Env> body) {
codeOnFacts.newA(new CodeFragment(head, body));
}
void onFactDo_keepBrackets(String head, IVF2, Env> body) {
codeOnFacts.newA(new CodeFragment(head, body, true));
}
List filterByPattern(String pat, Iterable items) {
return filter(items, i -> zipIt(pat, i) != null);
}
// pat = pattern with variables
// results are mappings with debracketed values
List> matchFacts(String pat) {
List> out = new ArrayList();
for (String fact : facts) {
Map map = zipIt(pat, fact);
if (map != null)
out.add(mapValues("tok_deRoundOrCurlyBracket",map));
}
return out;
}
// pat = pattern with variables
// results are mappings with debracketed values
List> matchFacts_keepBrackets(String pat) {
List> out = new ArrayList();
for (String fact : facts) {
Map map = zipIt_keepBrackets(pat, fact);
if (map != null)
out.add(map);
}
return out;
}
void openAllTheories() {
for (Map map : matchFacts_keepBrackets("theory $x $y"))
openTheory(tok_deRoundOrCurlyBracket(map.get("$x")), map.get("$y"));
}
void openTheory(String name, String body) {
//print("Raw theory: " + quote(s));
loadProgram(withoutLeadingLinesEmptyAfterTrim_autoUnindent(tok_deRoundOrCurlyBracket_keepFirstSpacing(body)));
print("Opened theory " + name);
}
void autoOpenTheories() {
onFactDo_keepBrackets("theory $x $y", (map, env) -> openTheory(tok_deRoundOrCurlyBracket(map.get("$x")), map.get("$y")));
}
// returns number of expectations checked
int checkExpectations() {
int n = 0;
// check if all expect (...) facts are met
for (Map map : matchFacts("expect $x")) {
assertContains(facts, firstValue(map));
++n;
}
// check if all don't expect (...) facts are met
for (Map map : matchFacts("don't expect $x")) {
assertDoesntContain(facts, firstValue(map));
++n;
}
return n;
}
void standardImports() {
if (standardImportsLoaded) return;
standardImportsLoaded = true;
onFactDo("import math", (map, env) -> {
print("Importing math functions");
philosophyBot1_math(this);
});
onFactDo("import bool", (map, env) -> {
print("Importing bool functions");
philosophyBot1_bool(this);
});
}
boolean hasFact(String fact) {
return contains(facts, fact);
}
boolean hasContradiction() { return hasFact("contradiction"); }
}static class Pair implements Comparable> {
A a;
B b;
Pair() {}
Pair(A a, B b) {
this.b = b;
this.a = a;}
public int hashCode() {
return hashCodeFor(a) + 2*hashCodeFor(b);
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Pair)) return false;
Pair t = (Pair) o;
return eq(a, t.a) && eq(b, t.b);
}
public String toString() {
return "<" + a + ", " + b + ">";
}
public int compareTo(Pair p) {
if (p == null) return 1;
int i = ((Comparable ) a).compareTo(p.a);
if (i != 0) return i;
return ((Comparable) b).compareTo(p.b);
}
}
static interface IF0 {
A get();
}static interface IFieldsToList {
Object[] _fieldsToList();
}static interface IF2 {
C get(A a, B b);
}static class AllOnAll {
List aList = new ArrayList();
List bList = new ArrayList();
List> todo = new LinkedList();
List> todo2 = new LinkedList();
synchronized void newA(A a) {
add(aList, a);
addPair(todo, intRange_last(aList), intRange(0, l(bList)));
}
synchronized void newAs(Iterable l) {
for (A a : unnull(l)) newA(a);
}
synchronized void newB(B b) {
add(bList, b);
addPair(todo, intRange(0, l(aList)), intRange_last(bList));
}
synchronized void newBs(Iterable l) {
for (B b : unnull(l)) newB(b);
}
synchronized Pair next() {
while (empty(todo2)) {
if (empty(todo)) return null;
Pair p = popFirst(todo);
addAll(todo2, outerProduct_pairs(subList(aList, p.a), subList(bList, p.b)));
}
return popFirst(todo2);
}
}static interface IF1 {
B get(A a);
}static interface IVF1 {
void get(A a);
}static interface IVF2 {
void get(A a, B b);
}static class HasGlobalID {
GlobalID globalID = aGlobalIDObjUnlessLoading();
}
final static class IntRange {
int start, end;
IntRange() {}
IntRange(int start, int end) {
this.end = end;
this.start = start;}
public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
int length() { return end-start; }
static String _fieldOrder = "start end";
public String toString() { return "[" + start + ";" + end + "]"; }
}static class GlobalID {
// We need 76 bits for 26^16 IDs
long a; // all bits used
int b; // 76-64=12 bits used; could be short. change to short when unstructure() is smarter
GlobalID() {}
GlobalID(String id) {
assertGlobalID(id);
BigInteger value = bigint(0);
for (int i = 0; i < l(id); i++)
value = plus(mul(value, 26), charDiff(id.charAt(i), 'a'));
a = value.longValue();
value = value.shiftRight(64);
b = value.shortValue();
}
public String toString() {
BigInteger value = bigint(b);
value = value.shiftLeft(32);
value = plus(value, (a >> 32) & 0xFFFFFFFFL);
value = value.shiftLeft(32);
value = plus(value, a & 0xFFFFFFFFL);
return bigintToGlobalID(value);
}
public boolean equals(Object o) {
if (!(o instanceof GlobalID)) return false;
return ((GlobalID) o).a == a && ((GlobalID) o).b == b;
}
public int hashCode() {
return (int) a;
}
}
static boolean reflection_isForbiddenMethod(Method m) {
return m.getDeclaringClass() == Object.class
&& eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}
static Set allInterfacesImplementedBy(Class c) {
if (c == null) return null;
HashSet set = new HashSet();
allInterfacesImplementedBy_find(c, set);
return set;
}
static void allInterfacesImplementedBy_find(Class c, Set set) {
if (c.isInterface() && !set.add(c)) return;
do {
for (Class intf : c.getInterfaces())
allInterfacesImplementedBy_find(intf, set);
} while ((c = c.getSuperclass()) != null);
}
static Method findMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args);
}
static boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static Method findStaticMethod(Class c, String method, Object... args) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (!m.getName().equals(method))
continue;
if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static boolean findStaticMethod_checkArgs(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length)
return false;
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i])))
return false;
return true;
}
static boolean nempty(Collection c) {
return !empty(c);
}
static boolean nempty(CharSequence s) {
return !empty(s);
}
static boolean nempty(Object[] o) { return !empty(o); }
static boolean nempty(byte[] o) { return !empty(o); }
static boolean nempty(int[] o) { return !empty(o); }
static boolean nempty(Map m) {
return !empty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean nempty(Object o) { return !empty(o); }
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static boolean any(Object pred, Iterable l) {
if (l != null) for (A a : l)
if (isTrue(callF(pred, a)))
return true;
return false;
}
static boolean any(IF1 pred, Iterable l) {
return any((Object) pred, l);
}
static boolean any(Iterable l, IF1 pred) {
return any(pred, l);
}
static List map(Iterable l, Object f) { return map(f, l); }
static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null) for (Object o : l)
x.add(callF(f, o));
return x;
}
static List map(Iterable l, F1 f) { return map(f, l); }
static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null) for (A o : l)
x.add(callF(f, o));
return x;
}
static List map(IF1 f, Iterable l) { return map(l, f); }
static List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
x.add(f.get(o));
return x;
}
static List map(IF1 f, A[] l) { return map(l, f); }
static List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
x.add(f.get(o));
return x;
}
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }
static List map(Object f, Map map) {
return map(map, f);
}
// map: func(key, value) -> list element
static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null) for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}
static int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static Set linkedCISet() {
return new LinkedTreeSet(ciSet());
}
static TreeSet litciset(String... items) {
TreeSet set = caseInsensitiveSet();
for (String a : items) set.add(a);
return set;
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static String tok_deRoundBracket(String s) {
return tok_isRoundBracketed(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
}
static List javaTokWithBrackets(String s) {
return javaTokPlusBrackets(s);
}
static int countCodeTokens(String s) {
return countTokens(s);
}
static int countCodeTokens(List tok) {
return countTokens(tok);
}
static boolean firstTokenEqic(List tok, String t) {
return eqic(get(tok, 1), t);
}
static boolean isCurlyBracketed(String s) {
return isCurlyBraced(s);
}
static String getCodeToken(List tok, int i) {
return get(tok, i*2+1);
}
static String uncurly_keepSpaces(String s) {
return tok_unCurlyBracket_keepSpaces(s);
}
static String indentx(String s) {
return indentx(indent_default, s);
}
static String indentx(int n, String s) {
return dropSuffix(repeat(' ', n), indent(n, s));
}
static String indentx(String indent, String s) {
return dropSuffix(indent, indent(indent, s));
}
static LinkedList cloneLinkedList(Iterable l) {
return l instanceof Collection ? cloneLinkedList((Collection) l) : asLinkedList(l);
}
static LinkedList cloneLinkedList(Collection l) {
if (l == null) return new LinkedList();
synchronized(collectionMutex(l)) {
return new LinkedList (l);
}
}
static A popFirst(List l) {
if (empty(l)) return null;
A a = first(l);
l.remove(0);
return a;
}
static A popFirst(Collection l) {
if (empty(l)) return null;
A a = first(l);
l.remove(a);
return a;
}
static List popFirst(int n, List l) {
List part = cloneSubList(l, 0, n);
removeSubList(l, 0, n);
return part;
}
static String sfu(Object o) { return structureForUser(o); }
static boolean checkCondition(Object condition, Object... args) {
return isTrue(callF(condition, args));
}
static boolean checkCondition(IF1 condition, A arg) {
return isTrue(callF(condition, arg));
}
static boolean isTrueOpt(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
return false;
}
static LinkedList mapToLinkedList(Iterable l, Object f) {
LinkedList x = new LinkedList();
if (l != null) for (Object o : l)
x.add(callF(f, o));
return x;
}
static LinkedList mapToLinkedList(Iterable l, IF1 f) {
return mapToLinkedList(l, (Object) f);
}
static String replaceVars(String s, Map map) {
return empty(map) ? s : join(replaceVars(javaTok(s), map));
}
static List replaceVars(List tok, Map map) {
if (empty(map)) return tok;
tok = cloneList(tok);
for (String var : keys(map))
jreplace(tok, var, map.get(var));
return tok;
}
static Map mapValues(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map))
m.put(key, callF(func, map.get(key)));
return m;
}
static Map mapValues(Map map, IF1 f) {
return mapValues(f, map);
}
static Map mapValues(Map map, Object func) {
return mapValues(func, map);
}
static String optRound(String s) {
return roundBracketIfMoreThanOneToken(s);
}
static Map mapKeys(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map))
m.put(callF(func, key), map.get(key));
return m;
}
static Map mapKeys(Map map, Object func) {
return mapKeys(func, map);
}
static Map mapKeys(Map map, IF1 func) {
return mapKeys(map, (Object) func);
}
static A lookupOrKeep(Map map, A key) {
return map != null && map.containsKey(key) ? map.get(key) : key;
}
static String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder out = new StringBuilder((int) (l(s)*1.5+2));
quote_impl(s, out);
return out.toString();
}
static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
static List tok_splitAtAmpersand(String s) {
return splitAtTokens(javaTokWithAllBrackets(s), "&");
}
static String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
static String[] dropFirst(String[] a) {
return drop(1, a);
}
static Object[] dropFirst(Object[] a) {
return drop(1, a);
}
static List dropFirst(List l) {
return dropFirst(1, l);
}
static List dropFirst(int n, Iterable i) { return dropFirst(n, toList(i)); }
static List dropFirst(Iterable i) { return dropFirst(toList(i)); }
static List dropFirst(int n, List l) {
return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
static List dropFirst(List l, int n) {
return dropFirst(n, l);
}
static String dropFirst(int n, String s) { return substring(s, n); }
static String dropFirst(String s, int n) { return substring(s, n); }
static String dropFirst(String s) { return substring(s, 1); }
static String tok_deRoundOrCurlyBracket(String s) {
return isCurlyBraced(s) || tok_isRoundBracketed(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
}
static Map gazelle_deepZip_keepBrackets(String inputA, String inputB, Object... __) {
Map map = gazelle_zip_keepBrackets(inputA, inputB);
if (map == null) return null;
Map map2 = similarEmptyMap(map);
for (String a : keys( map)) { String b = map.get(a);
if (tok_isRoundOrCurlyBracketed(a) && tok_isRoundOrCurlyBracketed(b)) {
String aa = tok_deRoundOrCurlyBracket(a);
String bb = tok_deRoundOrCurlyBracket(b);
Map subMap = gazelle_deepZip_keepBrackets(aa, bb, __);
if (subMap == null) return null;
if (!putAllStrictlyIC(map2, subMap)) return null;
} else
if (!strictPutIC(map2, a, b)) return null;
}
return map2;
}
static boolean all(Object pred, Collection l) {
if (l != null) for (Object o : l) if (!isTrue(callF(pred, o))) return false;
return true;
}
static boolean all(Iterable l, IF1 f) {
if (l != null) for (A a : l) if (!f.get(a)) return false;
return true;
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static boolean isDollarVar(String s) {
return startsWith(s, '$') && isJavaIdentifierAfter(s, 1);
}
static String replaceCodeTokensUsingMap(String s, Map map) {
return join(replaceCodeTokensUsingMap(javaTok(s), map));
}
static List replaceCodeTokensUsingMap(List tok, Map map) {
List out = emptyList(tok);
for (int i = 0; i < l(tok); i++) {
out.add(odd(i) ? lookupOrKeep(map, tok.get(i)) : tok.get(i));
}
return out;
}
static String replaceCodeTokensUsingMap(Map map, String s) {
return replaceCodeTokensUsingMap(s, map);
}
// TODO: extended multi-line strings
static int javaTok_n, javaTok_elements;
static boolean javaTok_opt = false;
static List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') { // allow multi-line strings, but not for '
++j;
break;
} else if (c2 == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
static void think(String thought) {
miniChat(thought);
}
static List getAndClearList(Collection l) {
if (l == null) return emptyList();
synchronized(collectionMutex(l)) {
List out = cloneList(l);
l.clear();
return out;
}
}
static List listMinusList(Collection l, Collection stuff) {
if (empty(stuff) && l instanceof List) return (List) l;
List l2 = cloneList(l);
for (Object o : stuff)
l2.remove(o);
return l2;
}
static A pnlWithHeading(String heading, A l) {
printAsciiHeading(heading);
return pnl(l);
}
static String tok_dropRoundBrackets(String s) {
return join(tok_dropRoundBrackets(javaTok(s)));
}
static List tok_dropRoundBrackets(List tok) {
for (int i = 1; i < l(tok); i+= 2) {
while (eqGetOneOf(tok, i, "(", ")")) {
tokAppend(tok, i-1, tok.get(i+1));
removeSubList(tok, i, i+2);
}
}
return tok;
}
static List filter(Iterable c, Object pred) {
if (pred instanceof F1) return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null) for (Object o : c)
if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
static List filter(Object pred, Iterable c) {
return filter(c, pred);
}
static List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null) for (B o : c)
if (pred.get(o))
x.add(o);
return x;
}
static List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
//ifclass IF1
static List filter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null) for (B o : c)
if (pred.get(o))
x.add(o);
return x;
}
static List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
//endif
static String withoutLeadingLinesEmptyAfterTrim_autoUnindent(String s) {
return autoUnindent(withoutLeadingLinesEmptyAfterTrim(s));
}
static String tok_deRoundOrCurlyBracket_keepFirstSpacing(String s) {
return isCurlyBraced(s) || tok_isRoundBracketed(s) ? join(dropFirstTwoAndLastThree(javaTok(s))) : s;
}
static > C assertContains(C c, A y) {
return assertContains(null, c, y);
}
static > C assertContains(String msg, C c, A y) {
if (!contains(c, y))
throw fail((msg != null ? msg + ": " : "") + y + " not contained in " + c);
return c;
}
static B firstValue(Map map) {
return first(values(map));
}
static > C assertDoesntContain(C c, A y) {
return assertDoesntContain(null, c, y);
}
static > C assertDoesntContain(String msg, C c, A y) {
if (contains(c, y))
throw fail((msg != null ? msg + ": " : "") + y + " contained in " + c);
return c;
}
static void philosophyBot1_math(PhilosophyBot1 bot) {
bot.addNativePredicate("$x >= $y",
(map) -> cmp(parseBigInt(map.get("$x")), parseBigInt(map.get("$y"))) >= 0);
bot.addNativePredicate("$x <= $y",
(map) -> cmp(parseBigInt(map.get("$x")), parseBigInt(map.get("$y"))) <= 0);
bot.addNativePredicate("$x > $y",
(map) -> cmp(parseBigInt(map.get("$x")), parseBigInt(map.get("$y"))) > 0);
bot.addNativePredicate("$x < $y",
(map) -> cmp(parseBigInt(map.get("$x")), parseBigInt(map.get("$y"))) < 0);
}
static void philosophyBot1_bool(PhilosophyBot1 bot) {
bot.addNativePredicate("true",
(map) -> true);
}
static int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
static void add(BitSet bs, int i) {
bs.set(i);
}
static boolean add(Collection c, A a) {
return c != null && c.add(a);
}
static void add(Container c, Component x) {
addToContainer(c, x);
}
static void addPair(Collection> c, A a, B b) {
if (c != null) c.add(pair(a, b));
}
static IntRange intRange_last(List l) {
int n = l(l);
return intRange(n-1, n);
}
static IntRange intRange(int start, int end) {
return new IntRange(start, end);
}
static String unnull(String s) {
return s == null ? "" : s;
}
static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
//ifclass Symbol
static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static void addAll(Collection c, Iterable b) {
if (c != null && b != null) for (A a : b) c.add(a);
}
static boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static boolean addAll(Collection c, B... b) {
return c != null && c.addAll(Arrays.asList(b));
}
static Map addAll(Map a, Map extends A,? extends B> b) {
if (a != null) a.putAll(b);
return a;
}
static IterableIterator> outerProduct_pairs(Collection lA, Collection lB) {
return outerProductPairs(lA, lB);
}
static IterableIterator> outerProduct_pairs(Pair extends Collection, ? extends Collection> p) {
return outerProduct_pairs(p.a, p.b);
}
static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static List subList(List l, int startIndex, int endIndex) {
if (l == null) return null;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex >= endIndex) return ll();
if (startIndex == 0 && endIndex == n) return l;
return l.subList(startIndex, endIndex);
}
static List subList(List l, IntRange r) {
return subList(l, r.start, r.end);
}
static GlobalID aGlobalIDObjUnlessLoading() {
return dynamicObjectIsLoading() ? null : aGlobalIDObj();
}
static boolean stdEq2(Object a, Object b) {
if (a == null) return b == null;
if (b == null) return false;
if (a.getClass() != b.getClass()) return false;
for (String field : allFields(a))
if (neq(getOpt(a, field), getOpt(b, field)))
return false;
return true;
}
static int stdHash2(Object a) {
if (a == null) return 0;
return stdHash(a, toStringArray(allFields(a)));
}
static String assertGlobalID(String s) {
return assertPossibleGlobalID(s);
}
static BigInteger bigint(String s) {
return new BigInteger(s);
}
static BigInteger bigint(long l) {
return BigInteger.valueOf(l);
}
static BigInteger plus(BigInteger a, BigInteger b) {
return a.add(b);
}
static BigInteger plus(BigInteger a, long b) {
return a.add(bigint(b));
}
static BigInteger mul(BigInteger a, BigInteger b) {
return a.multiply(b);
}
static BigInteger mul(BigInteger a, long b) {
return a.multiply(bigint(b));
}
static int charDiff(char a, char b) {
return (int) a-(int) b;
}
static int charDiff(String a, char b) {
return charDiff(stringToChar(a), b);
}
static String bigintToGlobalID(BigInteger value) {
char[] buf = new char[16];
for (int i = 16-1; i >= 0; i--) {
buf[i] = charPlus('a', mod(value, 26).intValue());
value = div(value, 26);
}
return str(buf);
}
static Method findMethod_cached(Object o, String method, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
_MethodCache cache = callOpt_getCache(((Class) o));
List methods = cache.cache.get(method);
if (methods != null) for (Method m : methods)
if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
return m;
return null;
} else {
_MethodCache cache = callOpt_getCache(o.getClass());
List methods = cache.cache.get(method);
if (methods != null) for (Method m : methods)
if (findMethod_checkArgs(m, args, false))
return m;
return null;
}
} catch (Exception __e) { throw rethrow(__e); } }
static TreeSet ciSet() {
return caseInsensitiveSet();
}
static TreeSet caseInsensitiveSet() {
return caseInsensitiveSet_treeSet();
}
static TreeSet caseInsensitiveSet(Collection c) {
return caseInsensitiveSet_treeSet(c);
}
static TreeSet treeSet() {
return new TreeSet();
}
static boolean tok_isRoundBracketed(String s) {
List tok = tok_combineRoundBrackets_keep(javaTok(s));
return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "(", ")");
}
static List dropFirstThreeAndLastThree(List l) {
return dropFirstAndLast(3, l);
}
static List javaTokPlusBrackets(String s) {
return tok_combineRoundOrCurlyBrackets_keep(javaTok(s));
}
static int countTokens(String s) {
return l(javaTokC(s));
}
static int countTokens(List tok) {
return l(tok)/2;
}
static boolean isCurlyBraced(String s) {
List tok = tok_combineCurlyBrackets_keep(javaTok(s));
return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}");
}
static String tok_unCurlyBracket_keepSpaces(String s) {
return isCurlyBraced(s) ? join(dropFirstTwoAndLastTwo(javaTok(s))) : s;
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static String repeat(char c, int n) {
n = Math.max(n, 0);
char[] chars = new char[n];
for (int i = 0; i < n; i++)
chars[i] = c;
return new String(chars);
}
static List repeat(A a, int n) {
n = Math.max(n, 0);
List l = new ArrayList(n);
for (int i = 0; i < n; i++)
l.add(a);
return l;
}
static List repeat(int n, A a) {
return repeat(a, n);
}
static int indent_default = 2;
static String indent(int indent) {
return repeat(' ', indent);
}
static String indent(int indent, String s) {
return indent(repeat(' ', indent), s);
}
static String indent(String indent, String s) {
return indent + s.replace("\n", "\n" + indent);
}
static String indent(String s) {
return indent(indent_default, s);
}
static List indent(String indent, List lines) {
List l = new ArrayList();
if (lines != null) for (String s : lines)
l.add(indent + s);
return l;
}
static LinkedList asLinkedList(Iterable s) {
if (s instanceof LinkedList) return ((LinkedList) s);
LinkedList l = new LinkedList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static List cloneSubList(List l, int startIndex, int endIndex) {
return newSubList(l, startIndex, endIndex);
}
static List cloneSubList(List l, int startIndex) {
return newSubList(l, startIndex);
}
static void removeSubList(List l, int from, int to) {
if (l != null) subList(l, from, to).clear();
}
static void removeSubList(List l, int from) {
if (l != null) subList(l, from).clear();
}
static String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
static String jreplace(String s, String in, String out) {
return jreplace(s, in, out, null);
}
static String jreplace(String s, String in, String out, Object condition) {
List tok = javaTok(s);
return jreplace(tok, in, out, condition) ? join(tok) : s;
}
// leaves tok properly tokenized
// returns true iff anything was replaced
static boolean jreplace(List tok, String in, String out) {
return jreplace(tok, in, out, false, true, null);
}
static boolean jreplace(List tok, String in, String out, Object condition) {
return jreplace(tok, in, out, false, true, condition);
}
static boolean jreplace(List tok, String in, String out, IF2