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; import javax.net.ssl.*; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; import javax.imageio.metadata.*; import javax.imageio.stream.*; import javax.swing.undo.UndoManager; import java.awt.datatransfer.StringSelection; import java.nio.file.Files; import java.nio.file.Path; public class main { public static String data = "\r\n\r\n -- rule\r\n \r\n what is X => I don't know what X is\r\n [expand \"X\"]\r\n \r\n -- test input\r\n \r\n what is a golden circle\r\n\r\n -- expected output\r\n \r\n I don't know what {a golden circle} is\r\n\r\n"; public static List> rules = new ArrayList(); public static List fulfillments = new ArrayList(); public static LinkedHashSet temporaryFacts = new LinkedHashSet(); public static List> dm_allRulesFromRulesModuleWithCommentsAndIDs() { return rules; } public static void dm_gazelle_setRuleComments_verbose(String ruleID, String comments) { set(objectWhere(rules, "c", ruleID), "b", comments); } public static Pair dm_textAndCommentForRule(String ruleID) { T3 t = objectWhere(rules, "c", ruleID); return t == null ? null : pair(t.a, t.b); } public static Pair dm_gazelle_addRuleWithComment(String text, String comment) { T3 t = objectWhere(rules, "a", text, "b", comment); if (t != null) return pair(t.c, false); String id = aGlobalID(); rules.add(t3(text, comment, id)); return pair(id, true); } public static List dm_gazelle_fulfillmentsForRule(String ruleID) { return objectsWhere(fulfillments, "rule", ruleID); } public static GazelleEvalContext dm_gazelle_stdEvalContext() { return dm_gazelle_stdEvalContext(dm_allRulesFromRulesModuleWithCommentsAndIDs()); } public static GazelleEvalContext dm_gazelle_stdEvalContext(List> rules) { return gazelle_stdEvalContext(rules); } public static String dm_gazelle_addTempFact(String text) { temporaryFacts.add(text); return aGlobalID(); } public static void main(final String[] args) throws Exception { pExperiment(); gazelle_fakery_performTest(data); } public static void set(Object o, String field, Object value) { if (o == null) return; if (o instanceof Class) set((Class) o, field, value); else try { Field f = set_findField(o.getClass(), field); f.setAccessible(true); smartSet(f, o, value); } catch (Exception e) { throw new RuntimeException(e); } } public static void set(Class c, String field, Object value) { if (c == null) return; try { Field f = set_findStaticField(c, field); f.setAccessible(true); smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } public static Field set_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()); } public static Field set_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()); } public static A objectWhere(Collection c, Object... data) { return findWhere(c, data); } public static Pair pair(A a, B b) { return new Pair(a, b); } public static Pair pair(A a) { return new Pair(a, a); } public static String aGlobalID() { return randomID(globalIDLength()); } public static T3 t3(A a, B b, C c) { return new T3(a, b, c); } public static List objectsWhere(Collection c, Object... data) { return filterByFields(c, data); } public static GazelleEvalContext gazelle_stdEvalContext(List> rules) { long startTime = sysNow(); GazelleEvalContext ctx = new GazelleEvalContext(); ctx.engine = new RuleEngine2(); ctx.engine.addRules2(rules); gazelle_changeInTypesForRulesWithMultipleInputs(ctx.engine); MultiMap statementsByRule = ai_gazelle_indexStatementsByRule(dm_gazelle_statementsFromAppliedRules()); ctx.dataByRule = mapValues("ai_gazelle_analyzeStatementsForRule", multiMapToMap(statementsByRule)); ctx.predictor = dm_gazelle_standardPredictor(); done2(startTime, "Making engine with " + n2(rules, "rule")); return ctx; } public static void pExperiment() { if (!isMain()) return; autoRestart(5); experimentIcon(); centerHigherConsole(); tt(); } public static void gazelle_fakery_performTest(String data, Object... __) { centerBigTTConsole(); TreeMap sections = minusSignSectionsCI(data); gazelle_fakery_gatherRulesFromSections(sections); dm_gazelle_wireStatementConditions(); pnlStruct(rules); gazelle_fakery_processInput_multi_v2(sections, __); } public static void smartSet(Field f, Object o, Object value) throws Exception { try { f.set(o, value); } catch (Exception e) { Class type = f.getType(); if (type == int.class && value instanceof Long) value = ((Long) value).intValue(); if (type == LinkedHashMap.class && value instanceof Map) { f.set(o, asLinkedHashMap((Map) value)); return; } throw e; } } public static A findWhere(Collection c, Object... data) { if (c != null) for (A x : c) if (checkFields(x, data)) return x; return null; } public static int randomID_defaultLength = 12; public static String randomID(int length) { return makeRandomID(length); } public static String randomID() { return randomID(randomID_defaultLength); } public static int globalIDLength() { return 16; } public static List filterByFields(Collection c, Object... data) { if (c == null) return null; List l = new ArrayList(); for (A x : c) if (checkFields(x, data)) l.add(x); return l; } public static long sysNow() { ping(); return System.nanoTime() / 1000000; } public static void gazelle_changeInTypesForRulesWithMultipleInputs(RuleEngine2 e) { for (RuleEngine2.Rule r : e.rules) { int i = 0; while (i < l(r.insWithType) && eq(r.insWithType.get(i).type, "standard")) ++i; if (i > 1) { reverseInPlace(subList(r.insWithType, 0, i)); for (int j = 1; j < i; j++) r.insWithType.get(j).type = "history-" + (j + 1); } } } public static MultiMap ai_gazelle_indexStatementsByRule(List statements) { MultiMap mm = new MultiMap(); for (Matches m : getMatchesX_all("Rule *: ...", statements)) mm.put(m.unq(0), m.rest()); return mm; } public static List dm_gazelle_statementsFromAppliedRules() { return keysList(dm_gazelle_statementsFromAppliedRules_multiSet()); } public 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; } public static Map mapValues(Map map, Object func) { return mapValues(func, map); } public static class ai_gazelle_analyzeStatementsForRule_Data { public MultiSet statements; public Set possibleVars, usedVars, unusedVars, varsUsedInGood, varsUsedInBad, varsUsedInGoodOnly, varsUsedInBadOnly; public Set unclearVars; public MultiMap goodMappings, badMappings, alwaysGoodMappings, alwaysBadMappings; public List> completeGoodMappings, completeBadMappings; public Map, PosNegScore> varScores; } public static ai_gazelle_analyzeStatementsForRule_Data ai_gazelle_analyzeStatementsForRule(Collection l) { Set possibleVars = asCISet(matchAny_firstGroups("possible variable *", l)); Set usedVars = asCISet(matchX_any_firstGroups("... variable * was used", l)); Set unusedVars = asCISet(listMinusSet(possibleVars, usedVars)); Set varsUsedInGood = asCISet(matchX_any_firstGroups("in a good mapping, variable * was used", l)); Set varsUsedInBad = asCISet(matchX_any_firstGroups("in a bad mapping, variable * was used", l)); Set unclearVars = setIntersection(varsUsedInGood, varsUsedInBad); MultiMap goodMappings = uniquifyMultiMapValues(pairsToMultiMap(matchX_any_firstAndSecondGroups("in a good mapping, variable * was mapped to *", l))); MultiMap badMappings = uniquifyMultiMapValues(pairsToMultiMap(matchX_any_firstAndSecondGroups("in a bad mapping, variable * was mapped to *", l))); MultiMap alwaysGoodMappings = multiMapDiff(goodMappings, badMappings); MultiMap alwaysBadMappings = multiMapDiff(badMappings, goodMappings); List> completeGoodMappings = map("safeUnstruct", matchX_any_firstGroups("a good mapping is *", l)); List> completeBadMappings = map("safeUnstruct", matchX_any_firstGroups("a bad mapping is *", l)); return nu(ai_gazelle_analyzeStatementsForRule_Data.class, "possibleVars", possibleVars, "usedVars", usedVars, "unusedVars", unusedVars, "varsUsedInGood", varsUsedInGood, "varsUsedInBad", varsUsedInBad, "unclearVars", unclearVars, "varsUsedInGoodOnly", setDiff(varsUsedInGood, varsUsedInBad), "varsUsedInBadOnly", setDiff(varsUsedInBad, varsUsedInGood), "goodMappings", goodMappings, "badMappings", badMappings, "alwaysGoodMappings", alwaysGoodMappings, "alwaysBadMappings", alwaysBadMappings, "completeGoodMappings", completeGoodMappings, "completeBadMappings", completeBadMappings); } public static Map> multiMapToMap(MultiMap m) { return m == null ? null : m.data; } public static GazellePredictor dm_gazelle_standardPredictor(Object... __) { return (ctx, r) -> { ai_gazelle_analyzeStatementsForRule_Data data = ctx.dataByRule.get(r.rule.globalID); return data == null ? null : ai_gazelle_predictor1_onData(r, data, __); }; } public static int done2_minPrint = 10; public static long done2(long startTime, String desc) { return done2(startTime, desc, done2_minPrint); } public static long done2(long startTime, String desc, int minPrint) { long time = sysNow() - startTime; saveTiming_noPrint(time); if (time >= minPrint) print(desc + " [" + time + " ms]"); return time; } public static long done2(String desc, long startTime) { return done2(startTime, desc); } public static long done2(long startTime) { return done2(startTime, ""); } public static String n2(long l) { return formatWithThousands(l); } public static String n2(Collection l) { return n2(l(l)); } public static String n2(double l, String singular) { return n2(l, singular, singular + "s"); } public static String n2(double l, String singular, String plural) { if (fraction(l) == 0) return n2((long) l, singular, plural); else return l + " " + plural; } public static String n2(long l, String singular, String plural) { return n_fancy2(l, singular, plural); } public static String n2(long l, String singular) { return n_fancy2(l, singular, singular + "s"); } public static String n2(Collection l, String singular) { return n2(l(l), singular); } public static String n2(Collection l, String singular, String plural) { return n_fancy2(l, singular, plural); } public static String n2(Map m, String singular, String plural) { return n_fancy2(m, singular, plural); } public static String n2(Map m, String singular) { return n2(l(m), singular); } public static String n2(Object[] a, String singular) { return n2(l(a), singular); } public static String n2(Object[] a, String singular, String plural) { return n_fancy2(a, singular, plural); } public static String n2(MultiSet ms, String singular, String plural) { return n_fancy2(ms, singular, plural); } public static boolean isMain() { return isMainProgram(); } public static double autoRestart_interval = 10; public static boolean autoRestart_on, autoRestart_debug, autoRestart_simulate; public static java.util.Timer autoRestart_timer; public static void autoRestart(double interval) { autoRestart_interval = interval; autoRestart(); } public static void autoRestart() { if (!isMain() || autoRestart_on) return; autoRestart_on = true; autoRestart_schedule(); preloadProgramTitle(); } public static void autoRestart_off() { if (!autoRestart_on) return; stopTimer(autoRestart_timer); autoRestart_timer = null; } public static void autoRestart_schedule() { autoRestart_timer = doLater_daemon(toMS(autoRestart_interval), "autoRestart_check"); } public static void autoRestart_check() { try { String newMD5; try { newMD5 = serverAutoRestartMD5(programID()); } catch (Throwable e) { return; } if (!isMD5(newMD5)) { if (autoRestart_debug) print("autoRestart: no server transpilation"); return; } if (autoRestart_localMD5 == null) autoRestart_localMD5 = md5(loadCachedTranspilation(programID())); String localMD5 = autoRestart_localMD5(); if (neq(localMD5, newMD5)) { if (autoRestart_simulate) print("Would upgrade now. " + localMD5 + " -> " + newMD5); else { infoBox("Upgrading " + programTitle()); restartWithDelay(500); sleep(); } } } finally { if (autoRestart_debug) print("autoRestart: Done"); autoRestart_schedule(); } } public static void experimentIcon() { consoleAndDefaultFrameIcon("#1101173"); } public static void centerHigherConsole() { if (headless()) return; setConsoleHeight(600); centerConsole(); } public static void tt() { typeWriterConsole(); } public static String tt(Object contents, Object... params) { return tag("tt", contents, params); } public static void centerBigTTConsole() { swing(new Runnable() { public void run() { try { tt(); setConsoleWidth(1000); setConsoleHeight(600); centerConsole(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tt();\r\n setConsoleWidth(1000);\r\n setConsoleHeight(600);\r\n centerConsole();"; } }); } public static TreeMap minusSignSectionsCI(String text) { return asCIMap(minusSignsSections(text)); } public static void gazelle_fakery_gatherRulesFromSections(TreeMap sections) { gazelle_fakery_clean(); { final Map __25 = keysStartingWith(sections, "rule"); for (String ruleID : keys(__25)) { String ruleText = __25.get(ruleID); List comments = new ArrayList(); ruleText = gazelle_processSquareBracketAnnotations(ruleText, comments); rules.add(t3(ruleText, lines(comments), ruleID)); } } } public static void dm_gazelle_wireStatementConditions() { for (T3 t : dm_gazelle_allRulesWithComment("in 2 = statement")) dm_gazelle_wireStatementConditions((t.c)); } public static void dm_gazelle_wireStatementConditions(String ruleID) { try { Pair p = dm_textAndCommentForRule(ruleID); List lines = tlft(p.a); Matches m = new Matches(); List comments = lines(p.b); boolean change = false; for (int i = 0; i < l(comments); i++) { if (match("in * = statement", comments.get(i), m)) { int line = parseInt(m.unq(0)); String s = dropPrefixTrim("+", get(lines, line - 1)); if (empty(s) || startsWith(s, "=>")) continue; String ruleID2 = dm_gazelle_findRuleForStatementCondition(s); if (ruleID2 == null) { print("No statement rule found for: " + s + ", making one"); ruleID2 = pairA(dm_gazelle_addRuleWithComment(s + "\n=> statement", "in = statement\n" + "made for rule " + ruleID + "\n" + p.b)); } comments.set(i, "in " + line + " = statement " + ruleID2); change = true; } } if (change) dm_gazelle_setRuleComments_verbose(ruleID, lines(comments)); } catch (Throwable __e) { _handleException(__e); } } public static void pnlStruct(Object o) { if (o instanceof Collection) pnlStruct(((Collection) o)); else if (o instanceof Map) pnlStruct(((Map) o)); else if (o != null) pnlStruct(ll(o)); } public static Collection pnlStruct(Collection l) { pnlStruct((Iterable) l); return l; } public static Iterable pnlStruct(Iterable l) { int i = 0; if (l != null) for (A a : l) print((++i) + ". " + struct_noStringSharing(a)); return l; } public static A[] pnlStruct(A[] l) { pnlStruct(asList(l)); return l; } public static Map pnlStruct(Map map) { pnl(map(map, new F2() { public Object get(A a, B b) { try { return sfu(a) + " = " + sfu(b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "sfu(a) + \" = \" + sfu(b)"; } })); return map; } public static void gazelle_fakery_processInput_multi_v2(TreeMap sections, Object... __) { int maxMonologue = optPar("maxMonologue", __, 5); ErrorCounter errorCounter = optPar("errorCounter", __, new ErrorCounter()); for (final String key : startingWithIC(keys(sections), "test input")) errorCounter.run(key, new Runnable() { public void run() { try { List inputLines = tlft(sections.get(key)); String expectedOutput = sections.get(replaceIC(key, "test input", "expected output")); String expectedTempFacts = sections.get(replaceIC(key, "test input", "expected temporary facts")); print("\nPROCESSING: " + key + "\n"); temporaryFacts.clear(); List lines = new ArrayList(); int nMonologue = 0; for (int i = 0; i < l(inputLines); i++) { String input = inputLines.get(i); String user = leadingSquareBracketStuff(input); input = dropActuallyLeadingSquareBracketStuff(input); gazelle_gatherFulfillments(ll(nu(GazelleLine.class, "text", input, "extras", litmap("user", user))), fulfillments, "debug", true); List l = dm_gazelle_reasonAboutChatInput_v2(user, input, paramsPlus(__, "preContext", subList(inputLines, 0, i), "respondingToHuman", nMonologue == 0, "requiredComment", null, "debug", true)); print("Got " + n2(l, "child", "children") + " with line types: " + collect("lineType", l)); for (GazelleTree t : l) { if (eq(t.lineType, "temporary fact")) temporaryFacts.add(printWithIndent("TEMP FACT> ", t.line)); else { lines.add(printWithIndent("OUT> ", t.line)); if (++nMonologue < maxMonologue) inputLines.add(t.line); } } } assertEqualsVerbose(lines, tlft(expectedOutput)); assertEqualsVerbose(asList(temporaryFacts), tlft(expectedTempFacts)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "List inputLines = tlft(sections.get(key));\r\n String expectedOutput..."; } }); errorCounter.print(); } public static LinkedHashMap asLinkedHashMap(Map map) { if (map instanceof LinkedHashMap) return (LinkedHashMap) map; LinkedHashMap m = new LinkedHashMap(); if (map != null) synchronized (collectionMutex(map)) { m.putAll(map); } return m; } public static boolean checkFields(Object x, Object... data) { for (int i = 0; i < l(data); i += 2) if (neq(getOpt(x, (String) data[i]), data[i + 1])) return false; return true; } public static String makeRandomID(int length) { return makeRandomID(length, defaultRandomGenerator()); } public static String makeRandomID(int length, Random random) { char[] id = new char[length]; for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26)); return new String(id); } public static volatile boolean ping_pauseAll; public static int ping_sleep = 100; public static volatile boolean ping_anyActions; public static Map ping_actions = newWeakHashMap(); public static ThreadLocal ping_isCleanUpThread = new ThreadLocal(); public static boolean ping() { if (ping_pauseAll || ping_anyActions) ping_impl(true); return true; } public static boolean ping_impl(boolean okInCleanUp) { try { if (ping_pauseAll && !isAWTThread()) { do Thread.sleep(ping_sleep); while (ping_pauseAll); return true; } if (ping_anyActions) { 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); } } public static int l(Object[] a) { return a == null ? 0 : a.length; } public static int l(boolean[] a) { return a == null ? 0 : a.length; } public static int l(byte[] a) { return a == null ? 0 : a.length; } public static int l(short[] a) { return a == null ? 0 : a.length; } public static int l(long[] a) { return a == null ? 0 : a.length; } public static int l(int[] a) { return a == null ? 0 : a.length; } public static int l(float[] a) { return a == null ? 0 : a.length; } public static int l(double[] a) { return a == null ? 0 : a.length; } public static int l(char[] a) { return a == null ? 0 : a.length; } public static int l(Collection c) { return c == null ? 0 : c.size(); } public static int l(Map m) { return m == null ? 0 : m.size(); } public static int l(CharSequence s) { return s == null ? 0 : s.length(); } public static long l(File f) { return f == null ? 0 : f.length(); } public 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"); } public static int l(MultiSet ms) { return ms == null ? 0 : ms.size(); } public static boolean eq(Object a, Object b) { return a == null ? b == null : a == b || b != null && a.equals(b); } public static List reverseInPlace(List l) { return reverseList(l); } public static List subList(List l, int startIndex) { return subList(l, startIndex, l(l)); } public 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); } public static List getMatchesX_all(String pat, Iterable l) { Matches m = new Matches(); List out = new ArrayList(); for (String s : unnull(l)) if (matchX(pat, s, m)) { out.add(m); m = new Matches(); } return out; } public static List keysList(Map map) { return cloneListSynchronizingOn(keys(map), map); } public static List keysList(MultiSet ms) { return ms == null ? null : keysList(ms.map); } public static class dm_gazelle_statementsFromAppliedRules_ByRule { public String ruleID; public MultiSet statements = new MultiSet(); } public static MultiSet dm_gazelle_statementsFromAppliedRules_multiSet() { List concepts = cloneList((List) dm_requireAndCall("#1021413/AppliedRules", "concepts")); Map ruleMap = new HashMap(); for (Object c : concepts) { try { String judgement = getString("judgement", c); String struct = getString("matchedRuleStruct", c); RuleEngine2_MatchedRule mr = (RuleEngine2_MatchedRule) (unstructureUnlessContainsAnonymousClasses(struct)); if (mr == null) continue; String ruleID = mr.rule.globalID; dm_gazelle_statementsFromAppliedRules_ByRule r = getOrCreate_f1(ruleMap, ruleID, new F1() { public dm_gazelle_statementsFromAppliedRules_ByRule get(String ruleID) { try { return nu(dm_gazelle_statementsFromAppliedRules_ByRule.class, "ruleID", ruleID); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "nu(dm_gazelle_statementsFromAppliedRules_ByRule, +ruleID)"; } }); r.statements.addAll(ai_gazelle_statementsFromAppliedRule(mr, judgement)); } catch (Throwable __e) { _handleException(__e); } } MultiSet out = new MultiSet(); for (dm_gazelle_statementsFromAppliedRules_ByRule r : values(ruleMap)) for (String s : keys(r.statements)) out.add("Rule " + r.ruleID + ": " + s, r.statements.get(s)); return out; } public static Map similarEmptyMap(Map m) { if (m instanceof TreeMap) return new TreeMap(((TreeMap) m).comparator()); if (m instanceof LinkedHashMap) return new LinkedHashMap(); return new HashMap(); } public static Set keys(Map map) { return map == null ? new HashSet() : map.keySet(); } public static Set keys(Object map) { return keys((Map) map); } public static Set keys(MultiSet ms) { return ms.keySet(); } public static Set keys(MultiMap mm) { return mm.keySet(); } public static Map> callF_cache = newDangerousWeakHashMap(); public static A callF(F0 f) { return f == null ? null : f.get(); } public static B callF(F1 f, A a) { return f == null ? null : f.get(a); } public static B callF(IF1 f, A a) { return f == null ? null : f.get(a); } public static C callF(F2 f, A a, B b) { return f == null ? null : f.get(a, b); } public static void callF(VF1 f, A a) { if (f != null) f.get(a); } public 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); } } public static ArrayList callF_makeCache(Class c) { ArrayList l = new ArrayList(); Class _c = c; do { for (Method m : _c.getDeclaredMethods()) if (m.getName().equals("get")) { m.setAccessible(true); l.add(m); } if (!l.isEmpty()) break; _c = _c.getSuperclass(); } while (_c != null); callF_cache.put(c, l); return l; } public static TreeSet asCISet(Iterable c) { return toCaseInsensitiveSet(c); } public static TreeSet asCISet(String... x) { return toCaseInsensitiveSet(x); } public static List matchAny_firstGroups(String pat, Iterable l) { Matches m = new Matches(); List out = new ArrayList(); for (String s : unnull(l)) if (match(pat, s, m)) out.add(m.unq(0)); return out; } public static List matchX_any_firstGroups(String pat, Iterable l) { Matches m = new Matches(); List out = new ArrayList(); for (String s : unnull(l)) if (matchX(pat, s, m)) out.add(m.unq(0)); return out; } public static List listMinusSet(Iterable l, Collection stuff) { if (empty(stuff)) return asList(l); Set set = asSet(stuff); List l2 = new ArrayList(); for (A a : l) if (!set.contains(a)) l2.add(a); return l2; } public static List listMinusSet(Iterable l, Collection stuff, Collection stuff2) { return listMinusSet(listMinusSet(l, stuff), stuff2); } public static Set setIntersection(Set a, Collection b) { Set set = similarEmptySet(a); Set bSet = asSet(b); for (A x : a) if (bSet.contains(x)) set.add(x); return set; } public static MultiMap uniquifyMultiMapValues(MultiMap mm) { return mm == null ? null : new MultiMap(mapValues("uniquify", mm.data)); } public static MultiMap pairsToMultiMap(List> l) { MultiMap mm = new MultiMap(); for (Pair p : unnull(l)) mm.put(p.a, p.b); return mm; } public static List> matchX_any_firstAndSecondGroups(String pat, Iterable l) { Matches m = new Matches(); List> out = new ArrayList(); for (String s : unnull(l)) if (matchX(pat, s, m)) out.add(pair(m.unq(0), m.unq(1))); return out; } public static MultiMap multiMapDiff(MultiMap mm1, MultiMap mm2) { return pairsToMultiMap(listMinusSet(multiMapToPairs(mm1), multiMapToPairs(mm2))); } public static List map(Iterable l, Object f) { return map(f, l); } public 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; } public static List map(Iterable l, F1 f) { return map(f, l); } public 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; } public 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; } public static List map(Object f, Object[] l) { return map(f, asList(l)); } public static List map(Object[] l, Object f) { return map(f, l); } public static List map(Object f, Map map) { return map(map, f); } public 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; } public static Object safeUnstruct(String s) { return unstructure(s, true); } public static A nu(Class c, Object... values) { A a = nuObject(c); setAll(a, values); return a; } public static Set setDiff(Set l, Collection stuff) { return setMinusSet(l, stuff); } public static String ai_gazelle_predictor1_onData(RuleEngine2_MatchedRule r, ai_gazelle_analyzeStatementsForRule_Data data, Object... __) { boolean debug = boolPar("debug", __); String prediction = containsAny(keys(r.map), data.varsUsedInBadOnly) ? "bad" : "good"; if (debug) print("predictor1: " + keys(r.map) + " => " + prediction); return prediction; } public static ThreadLocal saveTiming_last = new ThreadLocal(); public static void saveTiming(long ms) { print(ms + " ms"); saveTiming_noPrint(ms); } public static void saveTiming_noPrint(long ms) { saveTiming_last.set(ms); } public static volatile StringBuffer local_log = new StringBuffer(); public static volatile Appendable print_log = local_log; public static volatile int print_log_max = 1024 * 1024; public static volatile int local_log_max = 100 * 1024; public static boolean print_silent; public static Object print_byThread_lock = new Object(); public static volatile ThreadLocal print_byThread; public static volatile Object print_allThreads; public static volatile Object print_preprocess; public static void print() { print(""); } public static A print(String s, A o) { print((endsWithLetterOrDigit(s) ? s + ": " : s) + o); return o; } public static A print(A o) { ping_okInCleanUp(); if (print_silent) return o; String s = String.valueOf(o) + "\n"; print_noNewLine(s); return o; } public static void print_noNewLine(String s) { Object f = getThreadLocal(print_byThread_dontCreate()); if (f == null) f = print_allThreads; if (f != null) if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s))) return; print_raw(s); } public 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); } public static String formatWithThousands(long l) { return formatWithThousandsSeparator(l); } public static double fraction(double d) { return d % 1; } public static String n_fancy2(long l, String singular, String plural) { return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural); } public static String n_fancy2(Collection l, String singular, String plural) { return n_fancy2(l(l), singular, plural); } public static String n_fancy2(Map m, String singular, String plural) { return n_fancy2(l(m), singular, plural); } public static String n_fancy2(Object[] a, String singular, String plural) { return n_fancy2(l(a), singular, plural); } public static String n_fancy2(MultiSet ms, String singular, String plural) { return n_fancy2(l(ms), singular, plural); } public static boolean isMainProgram() { return creator() == null; } public static void preloadProgramTitle() { startThread(new Runnable() { public void run() { try { programTitle(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "programTitle();"; } }); } public static void stopTimer(java.util.Timer timer) { if (timer != null) timer.cancel(); } public static java.util.Timer doLater_daemon(long delay, final Object r) { final java.util.Timer timer = new java.util.Timer(true); timer.schedule(timerTask(r, timer), delay); return timer; } public static java.util.Timer doLater_daemon(double delaySeconds, final Object r) { return doLater_daemon(toMS(delaySeconds), r); } public static long toMS(double seconds) { return (long) (seconds * 1000); } public static int serverAutoRestartMD5_timeout = 10000; public static String serverAutoRestartMD5(String programID) { return loadPageSilentlyWithTimeout("http://botcompany.de/1010693/raw?id=" + psI(programID), serverAutoRestartMD5_timeout); } public static String serverAutoRestartMD5() { return serverAutoRestartMD5(programID()); } public static String programID() { return getProgramID(); } public static String programID(Object o) { return getProgramID(o); } public static boolean isMD5(String s) { return l(s) == 32 && isLowerHexString(s); } public static String md5(String text) { try { if (text == null) return "-"; return bytesToHex(md5_impl(toUtf8(text))); } catch (Exception __e) { throw rethrow(__e); } } public static String md5(byte[] data) { if (data == null) return "-"; return bytesToHex(md5_impl(data)); } public static MessageDigest md5_md; public static byte[] md5_impl(byte[] data) { try { return MessageDigest.getInstance("MD5").digest(data); } catch (Exception __e) { throw rethrow(__e); } } public static String md5(File file) { return md5OfFile(file); } public static String loadCachedTranspilation(String id) { try { return loadTextFilePossiblyGZipped(getCachedTranspilationFile(id)); } catch (Throwable __e) { return null; } } public static String autoRestart_localMD5; public static String autoRestart_localMD5() { if (autoRestart_localMD5 == null) autoRestart_localMD5 = md5(loadCachedTranspilation(programID())); return autoRestart_localMD5; } public static boolean neq(Object a, Object b) { return !eq(a, b); } public static JWindow infoBox(String text) { return infoMessage(text); } public static JWindow infoBox(String text, double seconds) { return infoMessage(text, seconds); } public static JWindow infoBox(Throwable e) { return infoMessage(e); } public static String programTitle() { return getProgramName(); } public static void restartWithDelay(int delay) { Object j = getJavaX(); call(j, "preKill"); call(j, "nohupJavax", smartJoin((String[]) get(j, "fullArgs")), call(j, "fullVMArguments")); sleep(delay); System.exit(0); sleep(); } public static volatile boolean sleep_noSleep; public static void sleep(long ms) { ping(); if (ms < 0) return; if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread"); try { Thread.sleep(ms); } catch (Exception e) { throw new RuntimeException(e); } } public static void sleep() { try { if (sleep_noSleep) throw fail("nosleep"); print("Sleeping."); sleepQuietly(); } catch (Exception __e) { throw rethrow(__e); } } public static void consoleAndDefaultFrameIcon(String icon) { consoleIcon(icon); setDefaultFrameIcon(icon); } public static boolean headless() { return isHeadless(); } public static void setConsoleHeight(int h) { setFrameHeight(consoleFrame(), h); } public static void centerConsole() { centerConsoleFrame(); } public static void centerConsole(int w, int h) { setConsoleSize(w, h); centerConsoleFrame(); } public static void typeWriterConsole() { if (isHeadless()) return; Font f = typeWriterFont(); consoleFont(f); consoleInputFont(f); } public static String tag(String tag) { return htag(tag); } public static String tag(String tag, Object contents, Object... params) { return htag(tag, str(contents), params); } public static String tag(String tag, StringBuilder contents, Object... params) { return htag(tag, contents, params); } public static String tag(String tag, StringBuffer contents, Object... params) { return htag(tag, contents, params); } public static Object swing(Object f) { return swingAndWait(f); } public static A swing(F0 f) { return (A) swingAndWait(f); } public static void setConsoleWidth(int w) { setFrameWidth(consoleFrame(), w); } public static RuntimeException rethrow(Throwable t) { if (t instanceof Error) _handleError((Error) t); throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } public static TreeMap asCIMap(Map map) { return asCaseInsensitiveMap(map); } public static Map minusSignsSections(String text) { List lines = lines(text); List l = indicesOfStartingWithTrim(lines, "--"); LinkedHashMap out = new LinkedHashMap(); if (nempty(l)) mapPutIfNemptyValue(out, "", rtrim(lines(subList(lines, 0, first(l))))); for (int i = 0; i < l(l); i++) { int i1 = l.get(i); int i2 = or(get(l, i + 1), l(lines)); String heading = trim(lines.get(i1)); int iHeading = 0; while (iHeading < l(heading) && heading.charAt(iHeading) == '-') iHeading++; heading = trim(substring(heading, iHeading)); out.put(heading, lines(subList(lines, i1 + 1, i2))); } return out; } public static void gazelle_fakery_clean() { rules.clear(); fulfillments.clear(); } public static Map keysStartingWith(String x, TreeMap map) { if (empty(x)) return map; String lastKey = lexicographicallyNextString(x); return map.subMap(x, true, lastKey, false); } public static Map keysStartingWith(TreeMap map, String x) { return keysStartingWith(x, map); } public static String gazelle_processSquareBracketAnnotations(String ruleText, List comments) { List lines = tlft(ruleText); while (isSquareBracketed(last(lines))) comments.add(deSquareBracket(popLast(lines))); int out = -1; for (int i = 0; i < l(lines); i++) { String s = lines.get(i); Pair p = splitTrailingSquareBracketStuff(s); if (startsWith(s, "=>")) out = i; if (nempty(p.b)) comments.add((out >= 0 ? i == out && i == l(lines) - 1 ? "out" : "out " + (i - out + 1) : "in " + (i + 1)) + " = " + p.b); lines.set(i, p.a); } return lines_rtrim(lines); } public static String lines(Iterable lines) { return fromLines(lines); } public static String lines(Object[] lines) { return fromLines(asList(lines)); } public static List lines(String s) { return toLines(s); } public static List> dm_gazelle_allRulesWithComment(final String comment) { List> l = dm_allRulesFromRulesModuleWithCommentsAndIDs(); return empty(comment) ? l : filter(l, new F1, Boolean>() { public Boolean get(T3 t) { try { return cic(tlft(t.b), comment); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cic(tlft(t.b), comment)"; } }); } public static List tlft(String s) { return toLinesFullTrim(s); } public static List tlft(File f) { return toLinesFullTrim(f); } public static boolean match(String pat, String s) { return match3(pat, s); } public static boolean match(String pat, String s, Matches matches) { return match3(pat, s, matches); } public static boolean match(String pat, List toks, Matches matches) { return match3(pat, toks, matches); } public static int parseInt(String s) { return empty(s) ? 0 : Integer.parseInt(s); } public static int parseInt(char c) { return Integer.parseInt(str(c)); } public static String dropPrefixTrim(String prefix, String s) { return trim(dropPrefix(prefix, s)); } public static A get(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } public static A get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } public static boolean get(boolean[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : false; } public 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) { f.setAccessible(true); 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()); } public static Object get_raw(Object o, String field) { try { Field f = get_findField(o.getClass(), field); f.setAccessible(true); return f.get(o); } catch (Exception e) { throw new RuntimeException(e); } } public static Object get(Class c, String field) { try { Field f = get_findStaticField(c, field); f.setAccessible(true); return f.get(null); } catch (Exception e) { throw new RuntimeException(e); } } public 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()); } public 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()); } public static Object get(String field, Object o) { return get(o, field); } public static boolean empty(Collection c) { return c == null || c.isEmpty(); } public static boolean empty(CharSequence s) { return s == null || s.length() == 0; } public static boolean empty(Map map) { return map == null || map.isEmpty(); } public static boolean empty(Object[] o) { return o == null || o.length == 0; } public 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)); } public static boolean empty(float[] a) { return a == null || a.length == 0; } public static boolean empty(int[] a) { return a == null || a.length == 0; } public static boolean empty(long[] a) { return a == null || a.length == 0; } public static boolean empty(byte[] a) { return a == null || a.length == 0; } public static boolean empty(MultiSet ms) { return ms == null || ms.isEmpty(); } public static boolean empty(File f) { return getFileSize(f) == 0; } public static boolean startsWith(String a, String b) { return a != null && a.startsWith(b); } public static boolean startsWith(String a, char c) { return nemptyString(a) && a.charAt(0) == c; } public static boolean startsWith(String a, String b, Matches m) { if (!startsWith(a, b)) return false; m.m = new String[] { substring(a, strL(b)) }; return true; } public 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; } public static String dm_gazelle_findRuleForStatementCondition(String s) { for (T3 t : dm_gazelle_allRulesWithComment("in = statement")) { Pair p = splitAtDoubleArrow_pair(t.a); if (p == null) { print("dm_gazelle_findRuleForStatementCondition skipping: " + t.a); continue; } if (eqic(p.a, s)) return t.c; } return null; } public static A pairA(Pair p) { return p == null ? null : p.a; } public static volatile PersistableThrowable _handleException_lastException; public static List _handleException_onException = synchroList(ll("printStackTrace2")); public 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); } } public static List ll(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; } public static String struct_noStringSharing(Object o) { structure_Data d = new structure_Data(); d.noStringSharing = true; return structure(o, d); } public static ArrayList asList(A[] a) { return a == null ? new ArrayList() : new ArrayList(Arrays.asList(a)); } public static ArrayList asList(int[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (int i : a) l.add(i); return l; } public static ArrayList asList(float[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (float i : a) l.add(i); return l; } public 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; } public static ArrayList asList(Producer p) { ArrayList l = new ArrayList(); A a; if (p != null) while ((a = p.next()) != null) l.add(a); return l; } public static ArrayList asList(Enumeration e) { ArrayList l = new ArrayList(); if (e != null) while (e.hasMoreElements()) l.add(e.nextElement()); return l; } public static A pnl(A l) { printNumberedLines(l); return l; } public static void pnl(Map map) { printNumberedLines(map); } public static void pnl(Object[] a) { printNumberedLines(a); } public static void pnl(String s) { printNumberedLines(lines(s)); } public static String sfu(Object o) { return structureForUser(o); } public static A optPar(ThreadLocal tl, A defaultValue) { A a = tl.get(); if (a != null) { tl.set(null); return a; } return defaultValue; } public static A optPar(ThreadLocal tl) { return optPar(tl, null); } public static Object optPar(Object[] params, String name) { return optParam(params, name); } public static Object optPar(String name, Object[] params) { return optParam(params, name); } public static A optPar(Object[] params, String name, A defaultValue) { return optParam(params, name, defaultValue); } public static A optPar(String name, Object[] params, A defaultValue) { return optParam(params, name, defaultValue); } public static List startingWithIC(Collection l, final String prefix) { return filter(unnull(l), new F1() { public Boolean get(String s) { try { return swic(s, prefix); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "swic(s, prefix)"; } }); } public static List startingWithIC(String prefix, Collection l) { return startingWithIC(l, prefix); } public static List replaceIC(List l, String a, String b) { List l2 = new ArrayList(); for (int i = 0; i < l(l); i++) { String s = l.get(i); l2.add(eqic(s, a) ? b : s); } return l2; } public static String replaceIC(String s, String a, String b) { return s.replaceAll("(?i)" + patternQuote(a), quoteReplacement(b)); } public static String leadingSquareBracketStuff(String s) { if (!startsWith(s, '[')) return null; return substring(s, 1, smartIndexOf(s, 1, ']')); } public static String dropActuallyLeadingSquareBracketStuff(String s) { return startsWith(s, "[") ? dropLeadingSquareBracketStuff(s) : s; } public static void gazelle_gatherFulfillments(List lines, List list_out, Object... __) { Integer maxEntries = (Integer) (optPar("maxEntries", __)); Flag cancel = (Flag) (optPar("cancel", __)); boolean debug = boolPar("debug", __); GazelleEvalContext ctx = (GazelleEvalContext) (optPar("ctx", __)); if (ctx == null) ctx = dm_gazelle_stdEvalContext(dm_gazelle_rulesOnFacts()); else { ctx = gazelle_cloneCtx(ctx); ctx.engine.dropRulesWhere(r -> !gazelle_isRuleOnFacts(r.text, r.comments)); } if (debug) print("Rules: " + l(ctx.engine.rules)); for (GazelleLine line : lines) { try { List children = gazelle_getChildren(new GazelleTree(ctx, line.text), __); if (debug) print("line " + line + ": children: " + children); for (GazelleTree t : gazelle_dropUnsatisfiedEntries(children)) { try { if (flagIsUp(cancel) || maxEntries != null && l(list_out) >= maxEntries) { print("Cancel"); return; } GazelleFulfillment f = nu(GazelleFulfillment.class, "line", t.parent.line, "varMap", struct(t.varMap()), "rule", t.ruleID(), "matchedRuleStruct", struct(t.mr), "context", "discord msg " + line.msgID); if (debug) printStruct(f); list_out.add(f); } catch (Throwable __e) { _handleException(__e); } } } catch (Throwable __e) { _handleException(__e); } } } public static HashMap litmap(Object... x) { HashMap map = new HashMap(); litmap_impl(map, x); return map; } public static void litmap_impl(Map map, Object... x) { for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null) map.put(x[i], x[i + 1]); } public static List dm_gazelle_reasonAboutChatInput_v2(String userName, String content, Object... __) { boolean debug = boolPar("debug", __); boolean debugRules = boolPar("debugRules", __) || debug; List preContext = (List) (optPar("preContext", __)); GazelleEvalContext ctx = (GazelleEvalContext) (optPar("ctx", __)); F0 contextMaker = (F0) (optPar("contextMaker", __)); if (ctx == null && contextMaker != null) { ctx = contextMaker.get(); if (debugRules) print("Called contextMaker, got " + n2(ctx.engine.rules, "rule")); } if (ctx == null) ctx = dm_gazelle_stdEvalContext(dm_gazelle_allRulesWithComment(optPar("requiredComment", __, "discord"))); Set acceptablePurposes = (Set) (optPar("acceptablePurposes", __)); if (debug) print(" == PROCESSING INPUT: " + content); ctx.engine.dropRulesWhere(r -> cicOneOf(r.comments, "in 1 = statement", "in = statement", "disable")); if (acceptablePurposes != null) { if (debugRules) print("Purposes: " + acceptablePurposes); ctx.engine.dropRulesWhere(r -> !acceptablePurposes.contains(unnull(r.purpose))); if (debugRules) print("Retaining " + n2(ctx.engine.rules, "rule")); } if (debugRules) print("Have rules: " + collect("globalID", ctx.engine.rules)); gazelle_addHelpers(ctx, __); Object[] params = litparams("firstConditionOnly", true, "dialogHistory", preContext, "debug", debug, "badComments", optPar("badComments", __), "acceptablePurposes", optPar("acceptablePurposes", __), "respondingToHuman", optPar("respondingToHuman", __), "skipSplitters", optPar("skipSplitters", __)); GazelleTree tree1 = (GazelleTree) (optPar("tree", __)); if (tree1 == null) tree1 = new GazelleTree(ctx, content); List l = dm_gazelle_getChildren(tree1, params); Map inputMap = gazelle_inputMapFromLineAndHistory(content, listPlus(preContext, content)); if (debug) print("reasonAbout inputMap=" + sfu(asTreeMap(inputMap))); dm_gazelle_matchAdditionalInput3(l, inputMap, __); if (nempty(userName) && !boolPar("skipUserName", __)) { GazelleTree tree2 = new GazelleTree(ctx, optCurly(userName) + " says: " + content); if (debug) print("Tree2: " + tree2); l.addAll(dm_gazelle_getChildren(tree2, paramsPlus(__, "tree2", true))); } Long userID = (Long) (optPar("userID", __)); if (userID != null && userID != 0 && !boolPar("skipUserID", __)) { GazelleTree tree3 = new GazelleTree(ctx, "user with id " + userID + " says: " + content); l.addAll(dm_gazelle_getChildren(tree3, paramsPlus(__, "tree3", true))); } if (boolPar("skipBad", __, true)) l = filter(l, new F1() { public Boolean get(GazelleTree t) { try { return neq(t.prediction, "bad"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "neq(t.prediction, \"bad\")"; } }); gazelle_sortChildren(l); dm_gazelle_matchStatements_v2(l, passParams(__, "debug", "dm_gazelle_matchStatementsDebug")); for (GazelleTree t : l) t.flush(); int n = l(l); l = gazelle_dropUnsatisfiedEntries(l); if (debug) print("Filtered out " + (n - l(l)) + " unsatisfied entries (keeping " + l(l) + ")"); if (!boolPar("keepDefaults", __)) gazelle_dropMatchedDefaultRules(l, __); return l; } public static Object[] paramsPlus(Object[] a1, Object... a2) { if (a2 == null) return a1; if (a1 == null) return a2; if (l(a1) == 1 && a1[0] instanceof Map) return new Object[] { mapPlus((Map) a1[0], a2) }; assertEvenLength(a1); assertEvenLength(a2); Map map = paramsToOrderedMap(a1); int n = l(a2); for (int i = 0; i < n; i += 2) { Object key = a2[i]; if (key != null) map.put(key, a2[i + 1]); } return mapToParams(map); } public static List collect(Collection c, String field) { return collectField(c, field); } public static List collect(String field, Collection c) { return collectField(c, field); } public static A printWithIndent(A o) { return printIndent(o); } public static A printWithIndent(String indent, A o) { return printIndent(indent, o); } public static void printWithIndent(int indent, Object o) { printIndent(indent, o); } public static A assertEqualsVerbose(Object x, A y) { assertEqualsVerbose((String) null, x, y); return y; } public static A assertEqualsVerbose(String msg, Object x, A y) { if (!eq(x, y)) { throw fail((msg != null ? msg + ": " : "") + (y) + " != " + (x)); } else print("OK: " + (x)); return y; } public static Throwable printStackTrace2(Throwable e) { print(getStackTrace2(e)); return e; } public static void printStackTrace2() { printStackTrace2(new Throwable()); } public static void printStackTrace2(String msg) { printStackTrace2(new Throwable(msg)); } public static Object collectionMutex(Object 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; } public static Object getOpt(Object o, String field) { return getOpt_cached(o, field); } public static Object getOpt(String field, Object o) { return getOpt_cached(o, field); } public static Object getOpt_raw(Object o, String field) { try { Field f = getOpt_findField(o.getClass(), field); if (f == null) return null; f.setAccessible(true); return f.get(o); } catch (Exception __e) { throw rethrow(__e); } } public static Object getOpt(Class c, String field) { try { if (c == null) return null; Field f = getOpt_findStaticField(c, field); if (f == null) return null; f.setAccessible(true); return f.get(null); } catch (Exception __e) { throw rethrow(__e); } } public 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; } public static Random defaultRandomGenerator() { return ThreadLocalRandom.current(); } public static Map newWeakHashMap() { return _registerWeakMap(synchroMap(new WeakHashMap())); } public static boolean isAWTThread() { if (isAndroid()) return false; if (isHeadless()) return false; return isAWTThread_awt(); } public static boolean isAWTThread_awt() { return SwingUtilities.isEventDispatchThread(); } public static boolean isTrue(Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); if (o == null) return false; if (o instanceof ThreadLocal) return isTrue(((ThreadLocal) o).get()); throw fail(getClassName(o)); } public static void failIfUnlicensed() { assertTrue("license off", licensed()); } public static Thread currentThread() { return Thread.currentThread(); } public static RuntimeException fail() { throw new RuntimeException("fail"); } public static RuntimeException fail(Throwable e) { throw asRuntimeException(e); } public static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); } public static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); } public static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); } public static Object call(Object o) { return callF(o); } public static Object call(Object o, String method, String[] arg) { return call(o, method, new Object[] { arg }); } public static Object call(Object o, String method, Object... args) { return call_cached(o, method, args); } public static String str(Object o) { return o == null ? "null" : o.toString(); } public static String str(char[] c) { return new String(c); } public static List reverseList(List l) { Collections.reverse(l); return l; } public static String unnull(String s) { return s == null ? "" : s; } public static Collection unnull(Collection l) { return l == null ? emptyList() : l; } public static List unnull(List l) { return l == null ? emptyList() : l; } public static Map unnull(Map l) { return l == null ? emptyMap() : l; } public static Iterable unnull(Iterable i) { return i == null ? emptyList() : i; } public static A[] unnull(A[] a) { return a == null ? (A[]) new Object[0] : a; } public static BitSet unnull(BitSet b) { return b == null ? new BitSet() : b; } public static Pair unnull(Pair p) { return p != null ? p : new Pair(null, null); } public static boolean matchX(String pat, String s) { return matchX(pat, s, null); } public static boolean matchX(String pat, String s, Matches m) { if (endsWith(pat, "...")) return matchStartX(pat, s, m); if (startsWith(pat, "...")) return matchEndX(pat, s, m); return match(pat, s, m); } public static ArrayList cloneListSynchronizingOn(Collection l, Object mutex) { if (l == null) return new ArrayList(); synchronized (mutex) { return new ArrayList(l); } } public static ArrayList cloneList(Iterable l) { return l instanceof Collection ? cloneList((Collection) l) : asList(l); } public static ArrayList cloneList(Collection l) { if (l == null) return new ArrayList(); synchronized (collectionMutex(l)) { return new ArrayList(l); } } public static Object dm_requireAndCall(String moduleLibID, String method, Object... args) { return dm_requireAndCallModule(moduleLibID, method, args); } public static String getString(Map map, Object key) { return map == null ? null : (String) map.get(key); } public static String getString(List l, int idx) { return (String) get(l, idx); } public static String getString(Object o, Object key) { if (o instanceof Map) return getString((Map) o, key); if (key instanceof String) return (String) getOpt(o, (String) key); throw fail("Not a string key: " + getClassName(key)); } public static String getString(String key, Object o) { return getString(o, (Object) key); } public static Object unstructureUnlessContainsAnonymousClasses(String s) { return structContainsAnonymousClasses(s) ? null : unstruct(s); } public static B getOrCreate_f1(Map map, A key, F1 create) { try { B b = map.get(key); if (b == null) mapPut(map, key, b = callF(create, key)); return b; } catch (Exception __e) { throw rethrow(__e); } } public static List ai_gazelle_statementsFromAppliedRule(RuleEngine2_MatchedRule r, String judgement) { if (r == null || r.rule == null) return new ArrayList(); if (nempty(judgement) && neq(judgement, "good")) judgement = "bad"; String ruleID = r.rule.globalID; String ruleIn = first(r.rule.in); if (ruleIn == null) return new ArrayList(); Map varMap = r.map; String tokenize = r.tokenizationFunction; List tok = (List) (callAndMake(tokenize, ruleIn)); List tokC = codeTokens(tok); Set possibleVars = asCISet(tokC); List statements = new ArrayList(); for (String a : keys(varMap)) { String b = varMap.get(a); statements.add(format("in a * mapping, variable " + quote(a) + " was used", judgement)); statements.add(format("in a * mapping, variable " + quote(a) + " was mapped to " + quote(b), judgement)); } for (String var : possibleVars) statements.add("possible variable " + quote(var)); statements.add(format("a * mapping is *", judgement, sfu(varMap))); return statements; } public static Collection values(Map map) { return map == null ? emptyList() : map.values(); } public static Collection values(MultiMap mm) { return mm == null ? emptyList() : concatLists(values(mm.data)); } public static Map newDangerousWeakHashMap() { return _registerDangerousWeakMap(synchroMap(new WeakHashMap())); } public static Map newDangerousWeakHashMap(Object initFunction) { return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction); } public static HashMap> callMC_cache = new HashMap(); public static String callMC_key; public static Method callMC_value; public static Object callMC(String method, String[] arg) { return callMC(method, new Object[] { arg }); } public static Object callMC(String method, Object... args) { try { Method me; if (callMC_cache == null) callMC_cache = new HashMap(); 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 matching arguments found in main"); } catch (Exception __e) { throw rethrow(__e); } } public 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) { m.setAccessible(true); multiMapPut(callMC_cache, m.getName(), m); } c = c.getSuperclass(); } } } public static String getClassName(Object o) { return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName(); } public 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); } } public 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; } public static TreeSet toCaseInsensitiveSet(Iterable c) { if (isCISet(c)) return (TreeSet) c; TreeSet set = caseInsensitiveSet(); addAll(set, c); return set; } public static TreeSet toCaseInsensitiveSet(String... x) { TreeSet set = caseInsensitiveSet(); addAll(set, x); return set; } public static Set asSet(Object[] array) { HashSet set = new HashSet(); for (Object o : array) if (o != null) set.add(o); return set; } public static Set asSet(String[] array) { TreeSet set = new TreeSet(); for (String o : array) if (o != null) set.add(o); return set; } public static Set asSet(Iterable l) { if (l instanceof Set) return (Set) l; HashSet set = new HashSet(); for (A o : unnull(l)) if (o != null) set.add(o); return set; } public static Set similarEmptySet(Collection m) { if (m instanceof TreeSet) return new TreeSet(((TreeSet) m).comparator()); if (m instanceof LinkedHashSet) return new LinkedHashSet(); return new HashSet(); } public static List uniquify(Collection l) { return uniquifyList(l); } public static List> multiMapToPairs(MultiMap mm) { List> out = new ArrayList(); for (A key : keys(mm)) for (B value : mm.get(key)) out.add(pair(key, value)); return out; } public static ArrayList emptyList() { return new ArrayList(); } public static ArrayList emptyList(int capacity) { return new ArrayList(max(0, capacity)); } public static ArrayList emptyList(Iterable l) { return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList(); } public static ArrayList emptyList(Class c) { return new ArrayList(); } public static Object unstructure(String text) { return unstructure(text, false); } public static Object unstructure(String text, final boolean allDynamic) { return unstructure(text, allDynamic, null); } public static int structure_internStringsLongerThan = 50; public static int unstructure_unquoteBufSize = 100; public static int unstructure_tokrefs; public abstract static class unstructure_Receiver { public abstract void set(Object o); } public static Object unstructure(String text, boolean allDynamic, Object classFinder) { if (text == null) return null; return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder); } public static Object unstructure_reader(BufferedReader reader) { return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null); } public static Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object _classFinder) { final boolean debug = unstructure_debug; final class X { public int i = -1; public final Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder(); public HashMap refs = new HashMap(); public HashMap tokrefs = new HashMap(); public HashSet concepts = new HashSet(); public HashMap classesMap = new HashMap(); public List stack = new ArrayList(); public String curT; public char[] unquoteBuf = new char[unstructure_unquoteBufSize]; public String unquote(String s) { return unquoteUsingCharArray(s, unquoteBuf); } public String t() { return curT; } public String tpp() { String t = curT; consume(); return t; } public void parse(final unstructure_Receiver out) { String t = t(); int refID = 0; if (structure_isMarker(t, 0, l(t))) { refID = parseInt(t.substring(1)); consume(); } final int _refID = refID; final int tokIndex = i; parse_inner(refID, tokIndex, new unstructure_Receiver() { public void set(Object o) { if (_refID != 0) refs.put(_refID, o); if (o != null) tokrefs.put(tokIndex, o); out.set(o); } }); } public void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) { String t = t(); Class c = classesMap.get(t); if (c == null) { if (t.startsWith("\"")) { String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan); out.set(s); return; } if (t.startsWith("'")) { out.set(unquoteCharacter(tpp())); return; } if (t.equals("bigint")) { out.set(parseBigInt()); return; } if (t.equals("d")) { out.set(parseDouble()); return; } if (t.equals("fl")) { out.set(parseFloat()); return; } if (t.equals("sh")) { consume(); t = tpp(); if (t.equals("-")) { t = tpp(); out.set((short) (-parseInt(t))); return; } out.set((short) parseInt(t)); return; } if (t.equals("-")) { consume(); t = tpp(); out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return; } if (isInteger(t) || isLongConstant(t)) { consume(); if (isLongConstant(t)) { out.set(parseLong(t)); return; } long l = parseLong(t); boolean isInt = l == (int) l; out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return; } if (t.equals("false") || t.equals("f")) { consume(); out.set(false); return; } if (t.equals("true") || t.equals("t")) { consume(); out.set(true); return; } if (t.equals("-")) { consume(); t = tpp(); out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return; } if (isInteger(t) || isLongConstant(t)) { consume(); if (isLongConstant(t)) { out.set(parseLong(t)); return; } long l = parseLong(t); boolean isInt = l == (int) l; out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return; } if (t.equals("File")) { consume(); File f = new File(unquote(tpp())); out.set(f); return; } if (t.startsWith("r") && isInteger(t.substring(1))) { consume(); int ref = Integer.parseInt(t.substring(1)); Object o = refs.get(ref); if (o == null) print("Warning: unsatisfied back reference " + ref); out.set(o); return; } if (t.startsWith("t") && isInteger(t.substring(1))) { consume(); int ref = Integer.parseInt(t.substring(1)); Object o = tokrefs.get(ref); if (o == null) print("Warning: unsatisfied token reference " + ref); out.set(o); return; } if (t.equals("hashset")) { parseHashSet(out); return; } if (t.equals("lhs")) { parseLinkedHashSet(out); return; } if (t.equals("treeset")) { parseTreeSet(out); return; } if (t.equals("ciset")) { parseCISet(out); return; } if (eqOneOf(t, "hashmap", "hm")) { consume(); parseMap(new HashMap(), out); return; } if (t.equals("lhm")) { consume(); parseMap(new LinkedHashMap(), out); return; } if (t.equals("tm")) { consume(); parseMap(new TreeMap(), out); return; } if (t.equals("cimap")) { consume(); parseMap(ciMap(), out); return; } if (t.equals("sync")) { consume(); if (t().equals("tm")) { consume(); { parseMap(synchronizedTreeMap(), out); return; } } if (t().equals("[")) { parseList(synchroList(), out); return; } { parseMap(synchronizedMap(), out); return; } } if (t.equals("{")) { parseMap(out); return; } if (t.equals("[")) { this.parseList(new ArrayList(), out); return; } if (t.equals("bitset")) { parseBitSet(out); return; } if (t.equals("array") || t.equals("intarray")) { parseArray(out); return; } if (t.equals("ba")) { consume(); String hex = unquote(tpp()); out.set(hexToBytes(hex)); return; } if (t.equals("boolarray")) { consume(); int n = parseInt(tpp()); String hex = unquote(tpp()); out.set(boolArrayFromBytes(hexToBytes(hex), n)); return; } if (t.equals("class")) { out.set(parseClass()); return; } if (t.equals("l")) { parseLisp(out); return; } if (t.equals("null")) { consume(); out.set(null); return; } if (eq(t, "c")) { consume("c"); t = t(); assertTrue(isJavaIdentifier(t)); concepts.add(t); } } if (eq(t, "j")) { consume("j"); out.set(parseJava()); return; } if (c == null && !isJavaIdentifier(t)) throw new RuntimeException("Unknown token " + (i + 1) + ": " + t); consume(); String className, fullClassName; if (eq(t(), ".")) { consume(); className = fullClassName = t + "." + assertIdentifier(tpp()); } else { className = t; fullClassName = "main$" + t; } if (c == null) { if (allDynamic) c = null; else c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName); if (c != null) classesMap.put(className, c); } boolean hasBracket = eq(t(), "("); if (hasBracket) consume(); boolean hasOuter = hasBracket && eq(t(), "this$1"); DynamicObject dO = null; Object o = null; final String thingName = t; if (c != null) { o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c); if (o instanceof DynamicObject) dO = (DynamicObject) o; } else { if (concepts.contains(t) && (c = findClass("Concept")) != null) o = dO = (DynamicObject) nuEmptyObject(c); else dO = new DynamicObject(); dO.className = className; } if (refID != 0) refs.put(refID, o != null ? o : dO); tokrefs.put(tokIndex, o != null ? o : dO); final LinkedHashMap fields = new LinkedHashMap(); final Object _o = o; final DynamicObject _dO = dO; if (hasBracket) { stack.add(new Runnable() { public void run() { try { if (eq(t(), ")")) { consume(")"); objRead(_o, _dO, fields); out.set(_o != null ? _o : _dO); } else { final String key = unquote(tpp()); if (!eq(tpp(), "=")) throw fail("= expected, got " + t() + " after " + quote(key) + " in object " + thingName); stack.add(this); parse(new unstructure_Receiver() { public void set(Object value) { fields.put(key, value); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \")\")) {\r\n consume(\")\");\r\n objRead(_o, _dO, ..."; } }); } else { objRead(o, dO, fields); out.set(o != null ? o : dO); } } public void objRead(Object o, DynamicObject dO, Map fields) { if (o != null) if (dO != null) { setOptAllDyn(dO, fields); } else { setOptAll_pcall(o, fields); } else for (String field : keys(fields)) dO.fieldValues.put(intern(field), fields.get(field)); if (o != null) pcallOpt_noArgs(o, "_doneLoading"); } public void parseSet(final Set set, final unstructure_Receiver out) { this.parseList(new ArrayList(), new unstructure_Receiver() { public void set(Object o) { set.addAll((List) o); out.set(set); } }); } public void parseLisp(final unstructure_Receiver out) { throw fail("class Lisp not included"); } public void parseBitSet(final unstructure_Receiver out) { consume("bitset"); consume("{"); final BitSet bs = new BitSet(); stack.add(new Runnable() { public void run() { try { if (eq(t(), "}")) { consume("}"); out.set(bs); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { bs.set((Integer) o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n ..."; } }); } public void parseList(final List list, final unstructure_Receiver out) { consume("["); stack.add(new Runnable() { public void run() { try { if (eq(t(), "]")) { consume("]"); out.set(list); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { list.add(o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"]\")) {\r\n consume(\"]\");\r\n out.set(list);\r\n ..."; } }); } public void parseArray(final unstructure_Receiver out) { final String type = tpp(); consume("{"); final List list = new ArrayList(); stack.add(new Runnable() { public void run() { try { if (eq(t(), "}")) { consume("}"); out.set(type.equals("intarray") ? toIntArray(list) : list.toArray()); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { list.add(o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(type.equals(\"..."; } }); } public Object parseClass() { consume("class"); consume("("); String name = unquote(tpp()); consume(")"); Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : findClass_fullName(name); if (c != null) return c; DynamicObject dO = new DynamicObject(); dO.className = "java.lang.Class"; name = dropPrefix("main$", name); dO.fieldValues.put("name", name); return dO; } public Object parseBigInt() { consume("bigint"); consume("("); String val = tpp(); if (eq(val, "-")) val = "-" + tpp(); consume(")"); return new BigInteger(val); } public Object parseDouble() { consume("d"); consume("("); String val = unquote(tpp()); consume(")"); return Double.parseDouble(val); } public Object parseFloat() { consume("fl"); String val; if (eq(t(), "(")) { consume("("); val = unquote(tpp()); consume(")"); } else { val = unquote(tpp()); } return Float.parseFloat(val); } public void parseHashSet(unstructure_Receiver out) { consume("hashset"); parseSet(new HashSet(), out); } public void parseLinkedHashSet(unstructure_Receiver out) { consume("lhs"); parseSet(new LinkedHashSet(), out); } public void parseTreeSet(unstructure_Receiver out) { consume("treeset"); parseSet(new TreeSet(), out); } public void parseCISet(unstructure_Receiver out) { consume("ciset"); parseSet(ciSet(), out); } public void parseMap(unstructure_Receiver out) { parseMap(new TreeMap(), out); } public Object parseJava() { String j = unquote(tpp()); Matches m = new Matches(); if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m)) return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2))); else { warn("Unknown Java object: " + j); return null; } } public void parseMap(final Map map, final unstructure_Receiver out) { consume("{"); stack.add(new Runnable() { public boolean v; public Object key; public void run() { if (v) { v = false; stack.add(this); if (!eq(tpp(), "=")) throw fail("= expected, got " + t() + " in map of size " + l(map)); parse(new unstructure_Receiver() { public void set(Object value) { map.put(key, value); if (eq(t(), ",")) consume(); } }); } else { if (eq(t(), "}")) { consume("}"); out.set(map); } else { v = true; stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { key = o; } }); } } } }); } public void consume() { curT = tok.next(); ++i; } public void consume(String s) { if (!eq(t(), s)) { throw fail(quote(s) + " expected, got " + quote(t())); } consume(); } public void parse_x(unstructure_Receiver out) { consume(); parse(out); while (nempty(stack)) popLast(stack).run(); } } Boolean b = DynamicObject_loading.get(); DynamicObject_loading.set(true); try { final Var v = new Var(); X x = new X(); x.parse_x(new unstructure_Receiver() { public void set(Object o) { v.set(o); } }); unstructure_tokrefs = x.tokrefs.size(); return v.get(); } finally { DynamicObject_loading.set(b); } } public static boolean unstructure_debug; public static Object nuObject(String className, Object... args) { try { return nuObject(classForName(className), args); } catch (Exception __e) { throw rethrow(__e); } } public static A nuObject(Class c, Object... args) { try { if (args.length == 0) return nuObjectWithoutArguments(c); Constructor m = nuObject_findConstructor(c, args); m.setAccessible(true); return (A) m.newInstance(args); } catch (Exception __e) { throw rethrow(__e); } } public static Constructor nuObject_findConstructor(Class c, Object... args) { for (Constructor m : c.getDeclaredConstructors()) { if (!nuObject_checkArgs(m.getParameterTypes(), args, false)) continue; return m; } throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : "")); } public static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) { 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; } public static void setAll(Object o, Map fields) { if (fields == null) return; for (String field : keys(fields)) set(o, field, fields.get(field)); } public static void setAll(Object o, Object... values) { failIfOddCount(values); for (int i = 0; i + 1 < l(values); i += 2) { String field = (String) values[i]; Object value = values[i + 1]; set(o, field, value); } } public static Set setMinusSet(Set l, Collection stuff) { if (empty(stuff)) return l; Set set = asSet(stuff); Set l2 = similarEmptySet(l); for (A a : l) if (!set.contains(a)) l2.add(a); return l2; } public static boolean boolPar(ThreadLocal tl) { return boolOptParam(tl); } public static boolean boolPar(Object[] __, String name) { return boolOptParam(__, name); } public static boolean boolPar(String name, Object[] __) { return boolOptParam(__, name); } public static boolean boolPar(String name, Object[] params, boolean defaultValue) { return optParam(params, name, defaultValue); } public static boolean containsAny(Collection a, Collection b) { if (empty(a) || empty(b)) return false; Set set = asSet(b); for (A x : a) if (contains(set, x)) return true; return false; } public static boolean containsAny(Map a, Collection b) { if (empty(a)) return false; if (b != null) for (A x : b) if (a.containsKey(x)) return true; return false; } public static boolean endsWithLetterOrDigit(String s) { return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1)); } public static void ping_okInCleanUp() { if (ping_pauseAll || ping_anyActions) ping_impl(true); } public static Object getThreadLocal(Object o, String name) { ThreadLocal t = (ThreadLocal) (getOpt(o, name)); return t != null ? t.get() : null; } public static A getThreadLocal(ThreadLocal tl) { return tl == null ? null : tl.get(); } public static ThreadLocal print_byThread_dontCreate() { return print_byThread; } public static boolean isFalse(Object o) { return eq(false, o); } public 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(); } public static void print_append(Appendable _buf, String s, int max) { try { synchronized (_buf) { _buf.append(s); if (!(_buf instanceof StringBuilder)) return; StringBuilder buf = (StringBuilder) _buf; max /= 2; if (buf.length() > max) 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); } } } catch (Exception __e) { throw rethrow(__e); } } public static String formatWithThousandsSeparator(long l) { return NumberFormat.getInstance(new Locale("en_US")).format(l); } public static String trim(String s) { return s == null ? null : s.trim(); } public static String trim(StringBuilder buf) { return buf.toString().trim(); } public static String trim(StringBuffer buf) { return buf.toString().trim(); } public static WeakReference creator_class; public static Object creator() { return creator_class == null ? null : creator_class.get(); } public static Thread startThread(Object runnable) { return startThread(defaultThreadName(), runnable); } public static Thread startThread(String name, Object runnable) { runnable = wrapAsActivity(runnable); return startThread(newThread(toRunnable(runnable), name)); } public static Thread startThread(Thread t) { _registerThread(t); t.start(); return t; } public static TimerTask timerTask(final Object r, final java.util.Timer timer) { return new TimerTask() { public void run() { if (!licensed()) timer.cancel(); else pcallF(r); } }; } public static String loadPageSilentlyWithTimeout(int timeout, String url) { return loadPageSilentlyWithTimeout(url, timeout); } public static String loadPageSilentlyWithTimeout(String url, int timeout) { try { url = loadPage_preprocess(url); URL _url = new URL(url); return loadPage(setURLConnectionTimeouts(_url.openConnection(), timeout), _url); } catch (Exception __e) { throw rethrow(__e); } } public static long psI(String snippetID) { return parseSnippetID(snippetID); } public static String programID; public static String getProgramID() { return nempty(programID) ? formatSnippetIDOpt(programID) : "?"; } public static String getProgramID(Class c) { String id = (String) getOpt(c, "programID"); if (nempty(id)) return formatSnippetID(id); return "?"; } public static String getProgramID(Object o) { return getProgramID(getMainClass(o)); } public static boolean isLowerHexString(String s) { for (int i = 0; i < l(s); i++) { char c = s.charAt(i); if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { } else return false; } return true; } public static String bytesToHex(byte[] bytes) { return bytesToHex(bytes, 0, bytes.length); } public static String bytesToHex(byte[] bytes, int ofs, int len) { StringBuilder stringBuilder = new StringBuilder(len * 2); for (int i = 0; i < len; i++) { String s = "0" + Integer.toHexString(bytes[ofs + i]); stringBuilder.append(s.substring(s.length() - 2, s.length())); } return stringBuilder.toString(); } public static byte[] toUtf8(String s) { try { return s.getBytes("UTF-8"); } catch (Exception __e) { throw rethrow(__e); } } public static boolean md5OfFile_verbose; public static String md5OfFile(String path) { return md5OfFile(newFile(path)); } public static String md5OfFile(File f) { try { if (!f.exists()) return "-"; if (md5OfFile_verbose) print("Getting MD5 of " + f); MessageDigest md5 = MessageDigest.getInstance("MD5"); FileInputStream in = new FileInputStream(f); try { byte[] buf = new byte[65536]; int l; while (true) { l = in.read(buf); if (l <= 0) break; md5.update(buf, 0, l); } return bytesToHex(md5.digest()); } finally { _close(in); } } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFilePossiblyGZipped(String fileName) { return loadTextFilePossiblyGZipped(fileName, null); } public static String loadTextFilePossiblyGZipped(String fileName, String defaultContents) { File gz = new File(fileName + ".gz"); return gz.exists() ? loadGZTextFile(gz) : loadTextFile(fileName, defaultContents); } public static String loadTextFilePossiblyGZipped(File fileName) { return loadTextFilePossiblyGZipped(fileName, null); } public static String loadTextFilePossiblyGZipped(File fileName, String defaultContents) { return loadTextFilePossiblyGZipped(fileName.getPath(), defaultContents); } public static File getCachedTranspilationFile(String id) { return newFile(getCodeProgramDir(id), "Transpilation"); } public static boolean infoMessage_alwaysOnTop = true; public static double infoMessage_defaultTime = 5.0; public static JWindow infoMessage(String text) { return infoMessage(text, infoMessage_defaultTime); } public static JWindow infoMessage(final String text, final double seconds) { printHidingCredentials(text); return infoMessage_noprint(text, seconds); } public static JWindow infoMessage_noprint(String text) { return infoMessage_noprint(text, infoMessage_defaultTime); } public static JWindow infoMessage_noprint(final String _text, final double seconds) { final String text = hideCredentials(_text); if (empty(text)) return null; logQuotedWithDate(infoBoxesLogFile(), text); if (isHeadless()) return null; return (JWindow) swingAndWait(new F0() { public Object get() { try { final JWindow window = showWindow(infoMessage_makePanel(text)); window.setSize(300, 150); moveToTopRightCorner(window); if (infoMessage_alwaysOnTop) window.setAlwaysOnTop(true); window.setVisible(true); if (seconds != 0) disposeWindowAfter(iround(seconds * 1000), window); return window; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JWindow window = showWindow(infoMessage_makePanel(text));\r\n window.s..."; } }); } public static JWindow infoMessage(Throwable e) { printStackTrace(e); return infoMessage(exceptionToStringShort(e)); } public static String getProgramName_cache; public static String getProgramName() { Lock __771 = downloadLock(); lock(__771); try { if (getProgramName_cache == null) getProgramName_cache = getSnippetTitleOpt(programID()); return getProgramName_cache; } finally { unlock(__771); } } public static void _onLoad_getProgramName() { startThread(new Runnable() { public void run() { try { getProgramName(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getProgramName();"; } }); } public static Class __javax; public static Class getJavaX() { try { return __javax; } catch (Exception __e) { throw rethrow(__e); } } public static String smartJoin(String[] args) { if (args.length == 1) return args[0]; String[] a = new String[args.length]; for (int i = 0; i < a.length; i++) a[i] = !isJavaIdentifier(args[i]) && !isQuoted(args[i]) ? quote(args[i]) : args[i]; return join(" ", a); } public static String smartJoin(List args) { return smartJoin(toStringArray(args)); } public static Object sleepQuietly_monitor = new Object(); public static void sleepQuietly() { try { assertFalse(isAWTThread()); synchronized (sleepQuietly_monitor) { sleepQuietly_monitor.wait(); } } catch (Exception __e) { throw rethrow(__e); } } public static void consoleIcon(String imageID) { frameIcon(consoleFrame(), or2(imageID, javaxDefaultIcon())); } public static void setDefaultFrameIcon(String icon) { setOptMC("makeFrame_defaultIcon", icon); } public static Boolean isHeadless_cache; public static boolean isHeadless() { if (isHeadless_cache != null) return isHeadless_cache; if (isAndroid()) return isHeadless_cache = true; if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true; try { SwingUtilities.isEventDispatchThread(); return isHeadless_cache = false; } catch (Throwable e) { return isHeadless_cache = true; } } public static JFrame setFrameHeight(JFrame frame, int h) { frame.setSize(frame.getWidth(), h); return frame; } public static JFrame setFrameHeight(int h, JFrame frame) { return setFrameHeight(frame, h); } public static JFrame consoleFrame() { return (JFrame) getOpt(get(getJavaX(), "console"), "frame"); } public static void centerConsoleFrame() { centerFrame(consoleFrame()); } public static void setConsoleSize(int w, int h) { setFrameSize(consoleFrame(), w, h); } public static Font typeWriterFont() { return typeWriterFont(iround(14 * getSwingFontScale())); } public static Font typeWriterFont(int size) { return new Font("Courier", Font.PLAIN, size); } public static void consoleFont(Font font) { callOpt(getConsoleTextArea_gen(), "setFont", font); } public static void consoleInputFont(final Font f) { { swing(new Runnable() { public void run() { try { JTextField input = consoleInputField(); if (input != null) { input.setFont(f); revalidateFrame(input); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JTextField input = consoleInputField();\r\n if (input != null) {\r\n inpu..."; } }); } } public static String htag(String tag) { return htag(tag, ""); } public static String htag(String tag, Object contents, Object... params) { String openingTag = hopeningTag(tag, params); String s = str(contents); if (empty(s) && neqic(tag, "script")) return dropLast(openingTag) + "/>"; return openingTag + s + ""; } public static void swingAndWait(Runnable r) { try { if (isAWTThread()) r.run(); else EventQueue.invokeAndWait(addThreadInfoToRunnable(r)); } catch (Exception __e) { throw rethrow(__e); } } public static Object swingAndWait(final Object f) { if (isAWTThread()) return callF(f); else { final Var result = new Var(); swingAndWait(new Runnable() { public void run() { try { result.set(callF(f)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; } }); return result.get(); } } public static A setFrameWidth(int w, A c) { return setFrameWidth(c, w); } public static A setFrameWidth(A c, int w) { JFrame f = getFrame(c); if (f != null) f.setSize(w, f.getHeight()); return c; } public static void _handleError(Error e) { call(javax(), "_handleError", e); } public static TreeMap asCaseInsensitiveMap(Map map) { if (isCIMap(map)) return (TreeMap) map; TreeMap m = ciMap(); m.putAll(map); return m; } public static List indicesOfStartingWithTrim(List l, String prefix) { List x = new ArrayList(); for (int i = 0; i < l(l); i++) if (startsWith(trim(l.get(i)), prefix)) x.add(i); return x; } public static boolean nempty(Collection c) { return !empty(c); } public static boolean nempty(CharSequence s) { return !empty(s); } public static boolean nempty(Object[] o) { return !empty(o); } public static boolean nempty(byte[] o) { return !empty(o); } public static boolean nempty(int[] o) { return !empty(o); } public static boolean nempty(Map m) { return !empty(m); } public static boolean nempty(Iterator i) { return i != null && i.hasNext(); } public static boolean nempty(Object o) { return !empty(o); } public static void mapPutIfNemptyValue(Map map, A key, String value) { if (map != null && key != null && nempty(value)) map.put(key, value); } public static String rtrim(String s) { if (s == null) return null; int i = s.length(); while (i > 0 && " \t\r\n".indexOf(s.charAt(i - 1)) >= 0) --i; return i < s.length() ? s.substring(0, i) : s; } public static Object first(Object list) { return first((Iterable) list); } public static A first(List list) { return empty(list) ? null : list.get(0); } public static A first(A[] bla) { return bla == null || bla.length == 0 ? null : bla[0]; } public static A first(IterableIterator i) { return first((Iterator) i); } public static A first(Iterator i) { return i == null || !i.hasNext() ? null : i.next(); } public static A first(Iterable i) { if (i == null) return null; Iterator it = i.iterator(); return it.hasNext() ? it.next() : null; } public static Character first(String s) { return empty(s) ? null : s.charAt(0); } public static A first(Pair p) { return p == null ? null : p.a; } public static A first(T3 t) { return t == null ? null : t.a; } public static A or(A a, A b) { return a != null ? a : b; } public static String substring(String s, int x) { return substring(s, x, strL(s)); } public 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); } public static String lexicographicallyNextString(String input) { final int lastCharPosition = input.length() - 1; String inputWithoutLastChar = input.substring(0, lastCharPosition); char lastChar = input.charAt(lastCharPosition); char incrementedLastChar = (char) (lastChar + 1); if (incrementedLastChar == ((char) 0)) return input + incrementedLastChar; return inputWithoutLastChar + incrementedLastChar; } public static boolean isSquareBracketed(String s) { return s != null && s.startsWith("[") && s.endsWith("]"); } public static A last(List l) { return empty(l) ? null : l.get(l.size() - 1); } public static char last(String s) { return empty(s) ? '#' : s.charAt(l(s) - 1); } public static int last(int[] a) { return l(a) != 0 ? a[l(a) - 1] : 0; } public static A last(A[] a) { return l(a) != 0 ? a[l(a) - 1] : null; } public static A last(Iterator it) { A a = null; while (it.hasNext()) { ping(); a = it.next(); } return a; } public static String deSquareBracket(String s) { if (startsWith(s, "[") && endsWith(s, "]")) return substring(s, 1, l(s) - 1); return s; } public static A popLast(List l) { return liftLast(l); } public static Pair splitTrailingSquareBracketStuff(String s) { if (!endsWith(s, "]")) return pair(s, ""); int i = smartLastIndexOf(s, '['); return pair(trimSubstring(s, 0, i), substring(s, i + 1, l(s) - 1)); } public static String lines_rtrim(Collection lines) { return rtrim_fromLines(lines); } public static String fromLines(Iterable lines) { StringBuilder buf = new StringBuilder(); if (lines != null) for (Object line : lines) buf.append(str(line)).append('\n'); return buf.toString(); } public static String fromLines(String... lines) { return fromLines(asList(lines)); } public static IterableIterator toLines(File f) { return linesFromFile(f); } public static List toLines(String s) { List lines = new ArrayList(); if (s == null) return lines; int start = 0; while (true) { int i = toLines_nextLineBreak(s, start); if (i < 0) { if (s.length() > start) lines.add(s.substring(start)); break; } lines.add(s.substring(start, i)); if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n') i += 2; else ++i; start = i; } return lines; } public static int toLines_nextLineBreak(String s, int start) { for (int i = start; i < s.length(); i++) { char c = s.charAt(i); if (c == '\r' || c == '\n') return i; } return -1; } public 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; } public static List filter(Object pred, Iterable c) { return filter(c, pred); } public static List filter(Iterable c, F1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o).booleanValue()) x.add(o); return x; } public static List filter(F1 pred, Iterable c) { return filter(c, pred); } public static List filter(Iterable c, IF1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o).booleanValue()) x.add(o); return x; } public static List filter(IF1 pred, Iterable c) { return filter(c, pred); } public static boolean cic(Collection l, String s) { return containsIgnoreCase(l, s); } public static boolean cic(String[] l, String s) { return containsIgnoreCase(l, s); } public static boolean cic(String s, char c) { return containsIgnoreCase(s, c); } public static boolean cic(String a, String b) { return containsIgnoreCase(a, b); } public static List toLinesFullTrim(String s) { List l = new ArrayList(); for (String line : toLines(s)) if (nempty(line = trim(line))) l.add(line); return l; } public static List toLinesFullTrim(File f) { List l = new ArrayList(); for (String line : linesFromFile(f)) if (nempty(line = trim(line))) l.add(line); return l; } public static boolean match3(String pat, String s) { return match3(pat, s, null); } public static boolean match3(String pat, String s, Matches matches) { if (pat == null || s == null) return false; return match3(pat, parse3_cachedInput(s), matches); } public static boolean match3(String pat, List toks, Matches matches) { List tokpat = parse3_cachedPattern(pat); return match3(tokpat, toks, matches); } public static boolean match3(List tokpat, List toks, Matches matches) { String[] m = match2(tokpat, toks); if (m == null) return false; if (matches != null) matches.m = m; return true; } public static String dropPrefix(String prefix, String s) { return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s; } public 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; } public static RuntimeException asRuntimeException(Throwable t) { if (t instanceof Error) _handleError((Error) t); return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } public static String getType(Object o) { return getClassName(o); } public static long getFileSize(String path) { return path == null ? 0 : new File(path).length(); } public static long getFileSize(File f) { return f == null ? 0 : f.length(); } public static boolean nemptyString(String s) { return s != null && s.length() > 0; } public static int strL(String s) { return s == null ? 0 : s.length(); } public static int listL(Collection l) { return l == null ? 0 : l.size(); } public static Pair splitAtDoubleArrow_pair(String s) { return splitAtDoubleArrow_pair(javaTokWithBrackets(s)); } public static Pair splitAtDoubleArrow_pair(List tok) { return listToPair(splitAtDoubleArrow(tok)); } public static boolean eqic(String a, String b) { if ((a == null) != (b == null)) return false; if (a == null) return true; return a.equalsIgnoreCase(b); } public 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); } public static List synchroList() { return Collections.synchronizedList(new ArrayList()); } public static List synchroList(List l) { return Collections.synchronizedList(l); } public static PersistableThrowable persistableThrowable(Throwable e) { return e == null ? null : new PersistableThrowable(e); } public static Throwable innerException(Throwable e) { return getInnerException(e); } public static boolean structure_showTiming, structure_checkTokenCount; public static String structure(Object o) { return structure(o, new structure_Data()); } public static String structure(Object o, structure_Data d) { StringWriter sw = new StringWriter(); d.out = new PrintWriter(sw); structure_go(o, d); String s = str(sw); if (structure_checkTokenCount) { print("token count=" + d.n); assertEquals("token count", l(javaTokC(s)), d.n); } return s; } public static void structure_go(Object o, structure_Data d) { structure_1(o, d); while (nempty(d.stack)) popLast(d.stack).run(); } public static void structureToPrintWriter(Object o, PrintWriter out) { structure_Data d = new structure_Data(); d.out = out; structure_go(o, d); } public static boolean structure_allowShortening = false; public static class structure_Data { public PrintWriter out; public int stringSizeLimit; public int shareStringsLongerThan = 20; public boolean noStringSharing; public IdentityHashMap seen = new IdentityHashMap(); public HashMap strings = new HashMap(); public HashSet concepts = new HashSet(); public HashMap> fieldsByClass = new HashMap(); public HashMap persistenceInfo = new HashMap(); public int n; public List stack = new ArrayList(); public structure_Data append(String token) { out.print(token); ++n; return this; } public structure_Data append(int i) { out.print(i); ++n; return this; } public structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; } public structure_Data app(String token) { out.print(token); return this; } public structure_Data app(int i) { out.print(i); return this; } } public static void structure_1(final Object o, final structure_Data d) { try { if (o == null) { d.append("null"); return; } Class c = o.getClass(); boolean concept = false; List lFields = d.fieldsByClass.get(c); if (lFields == null) { if (o instanceof Number) { PrintWriter out = d.out; if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; } if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; } if (o instanceof Short) { short s = ((Short) o).shortValue(); d.append("sh ", 2); out.print(s); d.n += s < 0 ? 2 : 1; return; } if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; } if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; } if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; } } if (o instanceof Boolean) { d.append(((Boolean) o).booleanValue() ? "t" : "f"); return; } if (o instanceof Character) { d.append(quoteCharacter((Character) o)); return; } if (o instanceof File) { d.append("File ").append(quote(((File) o).getPath())); return; } Integer ref = d.seen.get(o); if (o instanceof String && ref == null) ref = d.strings.get((String) o); if (ref != null) { d.append("t").app(ref); return; } if (!(o instanceof String)) d.seen.put(o, d.n); else { String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o; if (!d.noStringSharing) { if (d.shareStringsLongerThan == Integer.MAX_VALUE) d.seen.put(o, d.n); if (l(s) >= d.shareStringsLongerThan) d.strings.put(s, d.n); } quoteToPrintWriter(s, d.out); d.n++; return; } if (o instanceof Set) { if (((Set) o) instanceof TreeSet) { d.append(isCISet_gen(((Set) o)) ? "ciset" : "treeset"); structure_1(new ArrayList(((Set) o)), d); return; } d.append(((Set) o) instanceof LinkedHashSet ? "lhs" : "hashset"); structure_1(new ArrayList(((Set) o)), d); return; } String name = c.getName(); if (o instanceof Collection && !startsWith(name, "main$")) { if (name.equals("java.util.Collections$SynchronizedList") || name.equals("java.util.Collections$SynchronizedRandomAccessList")) d.append("sync"); d.append("["); final int l = d.n; final Iterator it = ((Collection) o).iterator(); d.stack.add(new Runnable() { public void run() { try { if (!it.hasNext()) d.append("]"); else { d.stack.add(this); if (d.n != l) d.append(", "); structure_1(it.next(), d); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.sta..."; } }); return; } if (o instanceof Map && !startsWith(name, "main$")) { if (o instanceof LinkedHashMap) d.append("lhm"); else if (o instanceof HashMap) d.append("hm"); else if (o instanceof TreeMap) d.append(isCIMap_gen(((TreeMap) o)) ? "cimap" : "tm"); else if (name.equals("java.util.Collections$SynchronizedMap")) d.append("sync"); else if (name.equals("java.util.Collections$SynchronizedSortedMap")) { d.append("sync tm", 2); } d.append("{"); final int l = d.n; final Iterator it = ((Map) o).entrySet().iterator(); d.stack.add(new Runnable() { public boolean v; public Map.Entry e; public void run() { if (v) { d.append("="); v = false; d.stack.add(this); structure_1(e.getValue(), d); } else { if (!it.hasNext()) d.append("}"); else { e = (Map.Entry) it.next(); v = true; d.stack.add(this); if (d.n != l) d.append(", "); structure_1(e.getKey(), d); } } } }); return; } if (c.isArray()) { if (o instanceof byte[]) { d.append("ba ").append(quote(bytesToHex((byte[]) o))); return; } final int n = Array.getLength(o); if (o instanceof boolean[]) { String hex = boolArrayToHex((boolean[]) o); int i = l(hex); while (i > 0 && hex.charAt(i - 1) == '0' && hex.charAt(i - 2) == '0') i -= 2; d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return; } String atype = "array", sep = ", "; if (o instanceof int[]) { atype = "intarray"; sep = " "; } d.append(atype).append("{"); d.stack.add(new Runnable() { public int i; public void run() { if (i >= n) d.append("}"); else { d.stack.add(this); if (i > 0) d.append(", "); structure_1(Array.get(o, i++), d); } } }); return; } if (o instanceof Class) { d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return; } if (o instanceof Throwable) { d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return; } if (o instanceof BitSet) { BitSet bs = (BitSet) o; d.append("bitset{", 2); int l = d.n; for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { if (d.n != l) d.append(", "); d.append(i); } d.append("}"); return; } if (name.startsWith("java.") || name.startsWith("javax.")) { d.append("j ").append(quote(str(o))); return; } String dynName = shortDynamicClassName(o); if (concept && !d.concepts.contains(dynName)) { d.concepts.add(dynName); d.append("c "); } TreeSet fields = new TreeSet(new Comparator() { public int compare(Field a, Field b) { return stdcompare(a.getName(), b.getName()); } }); Class cc = c; while (cc != Object.class) { for (Field field : getDeclaredFields_cached(cc)) { String fieldName = field.getName(); if (fieldName.equals("_persistenceInfo")) d.persistenceInfo.put(c, field); if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0) continue; fields.add(field); } cc = cc.getSuperclass(); } lFields = asList(fields); for (int i = 0; i < l(lFields); i++) { Field f = lFields.get(i); if (f.getName().equals("this$1")) { lFields.remove(i); lFields.add(0, f); break; } } d.fieldsByClass.put(c, lFields); } else { Integer ref = d.seen.get(o); if (ref != null) { d.append("t").app(ref); return; } d.seen.put(o, d.n); } Field persistenceInfoField = (Field) (d.persistenceInfo.get(c)); Map persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o); LinkedHashMap fv = new LinkedHashMap(); for (Field f : lFields) { Object value; try { value = f.get(o); } catch (Exception e) { value = "?"; } if (value != null && (persistenceInfo == null || !Boolean.FALSE.equals(persistenceInfo.get(f.getName())))) fv.put(f.getName(), value); } String name = c.getName(); String shortName = dropPrefix("main$", name); if (startsWithDigit(shortName)) shortName = name; if (concept && eq(fv.get("className"), shortName)) fv.remove("className"); if (o instanceof DynamicObject) { fv.putAll((Map) fv.get("fieldValues")); fv.remove("fieldValues"); shortName = shortDynamicClassName(o); fv.remove("className"); } String singleField = fv.size() == 1 ? first(fv.keySet()) : null; d.append(shortName); final int l = d.n; final Iterator it = fv.entrySet().iterator(); d.stack.add(new Runnable() { public void run() { try { if (!it.hasNext()) { if (d.n != l) d.append(")"); } else { Map.Entry e = (Map.Entry) it.next(); d.append(d.n == l ? "(" : ", "); d.append((String) e.getKey()).append("="); d.stack.add(this); structure_1(e.getValue(), d); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public static List printNumberedLines(List l) { printNumberedLines((Collection) l); return l; } public static void printNumberedLines(Map map) { printNumberedLines(mapToLines(map)); } public static A printNumberedLines(A l) { int i = 0; if (l != null) for (Object a : l) print((++i) + ". " + str(a)); return l; } public static void printNumberedLines(Object[] l) { printNumberedLines(asList(l)); } public static void printNumberedLines(Object o) { printNumberedLines(lines(str(o))); } public static String structureForUser(Object o) { return beautifyStructure(struct_noStringSharing(o)); } public static A optParam(ThreadLocal tl, A defaultValue) { return optPar(tl, defaultValue); } public static A optParam(ThreadLocal tl) { return optPar(tl); } public 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; } public static Object optParam(Object[] opt, String name) { return optParam(opt, name, null); } public static boolean swic(String a, String b) { return startsWithIgnoreCase(a, b); } public static boolean swic(String a, String b, Matches m) { if (!swic(a, b)) return false; m.m = new String[] { substring(a, l(b)) }; return true; } public static String patternQuote(String s) { return s.length() == 0 ? "" : Pattern.quote(s); } public static String quoteReplacement(String s) { return Matcher.quoteReplacement(s); } public static int smartIndexOf(String s, String sub, int i) { if (s == null) return 0; i = s.indexOf(sub, min(i, l(s))); return i >= 0 ? i : l(s); } public static int smartIndexOf(String s, int i, char c) { return smartIndexOf(s, c, i); } public static int smartIndexOf(String s, char c, int i) { if (s == null) return 0; i = s.indexOf(c, min(i, l(s))); return i >= 0 ? i : l(s); } public static int smartIndexOf(String s, String sub) { return smartIndexOf(s, sub, 0); } public static int smartIndexOf(String s, char c) { return smartIndexOf(s, c, 0); } public static int smartIndexOf(List l, A sub) { return smartIndexOf(l, sub, 0); } public static int smartIndexOf(List l, int start, A sub) { return smartIndexOf(l, sub, start); } public static int smartIndexOf(List l, A sub, int start) { int i = indexOf(l, sub, start); return i < 0 ? l(l) : i; } public static String dropLeadingSquareBracketStuff(String s) { return trimSubstring(s, indexOf(s, ']') + 1); } public static List> dm_gazelle_rulesOnFacts() { return filter(dm_allRulesFromRulesModuleWithCommentsAndIDs(), t -> gazelle_isRuleOnFacts(t.a, t.b)); } public static GazelleEvalContext gazelle_cloneCtx(GazelleEvalContext ctx) { GazelleEvalContext ctx2 = shallowClone(ctx); ctx2.engine = new RuleEngine2(); ctx2.engine.copyRulesFrom(ctx.engine); return ctx2; } public static boolean gazelle_isRuleOnFacts(String text, List comments) { return contains(comments, "in = statement"); } public static boolean gazelle_isRuleOnFacts(String text, String comments) { return gazelle_isRuleOnFacts(text, tlft(comments)); } public static List gazelle_getChildren(GazelleTree tree, Object... __) { if (tree == null) return null; if (tree.children != null) return tree.children; tree.children = new ArrayList(); double qualityCutOff = optPar("qualityCutOff", __, -0.75); List dialogHistory = (List) (optPar("dialogHistory", __)); boolean debug = boolPar("debug", __); if (tree.ctx == null) tree.setContext(assertNotNull("evalContext", (GazelleEvalContext) callF(assertNotNull("makeEvalContext", (Object) optPar("makeEvalContext", __))))); GazelleEvalContext ctx = tree.ctx; RuleEngine2 engine = ctx.engine; Map inputMap = gazelle_inputMapFromLineAndHistory(tree.line, concatLists(dialogHistory, tree.history())); if (boolPar("respondingToHuman", __)) inputMap.put("_respondingToHuman", "true"); if (debug) print("inputMap=" + sfu(asTreeMap(inputMap))); if (!boolPar("skipSplitters", __)) for (RuleEngine2.SimplifyWithRule rule : engine.splitterRules()) { try { Collection out = gazelle_executeSplitterRule(engine, rule, tree.line); if (empty(out)) continue; GazelleTree child = new GazelleTree(joinWithVBar(out)); child.ctx = ctx; child.isSplitNode = true; tree.add(child); for (String line : out) child.add(new GazelleTree(line)); } catch (Throwable __e) { _handleException(__e); } } boolean firstConditionOnly = boolPar("firstConditionOnly", __); Object[] params = litobjectarray("debug", optPar("debug", __), "tree", tree); List l = sortByMethodDesc("qualitySum", firstConditionOnly ? ai_ruleEngine2_rulesForInput_5(engine, inputMap, params) : ai_ruleEngine2_rulesForInput_5_allConditions(engine, inputMap, params)); for (RuleEngine2_MatchedRule r : l) { double quality = r.relativeQuality(); double cutOff = qualityCutOff; if (r.rule != null && r.rule.qualityCutOff != null) cutOff = r.rule.qualityCutOff; if (quality < cutOff && boolPar("skipBad", __, true)) { if (debug) print("Match under quality (" + quality + "/" + qualityCutOff + "): " + r); continue; } String line = r.outText(); GazelleTree child = new GazelleTree(line); child.ctx = ctx; child.mr = r; if (r.rule != null) child.lineType = r.rule.outType; gazelle_addPredictionToTreeNode(child); tree.add(child); } gazelle_sortChildren(tree); return tree.children; } public static List gazelle_dropUnsatisfiedEntries(List l) { return antiFilter(l, t -> t.mr != null && t.mr.moreConditions()); } public static boolean flagIsUp(Flag f) { return f != null && f.isUp(); } public static String struct(Object o) { return structure(o); } public static String struct(Object o, structure_Data data) { return structure(o, data); } public static A printStruct(String prefix, A a) { printStructure(prefix, a); return a; } public static A printStruct(A a) { printStructure(a); return a; } public static boolean cicOneOf(String s, String... l) { for (String x : l) if (cic(s, x)) return true; return false; } public static boolean cicOneOf(Collection l, String... bla) { for (String x : unnull(l)) if (eqicOneOf(x, bla)) return true; return false; } public static void gazelle_addHelpers(GazelleEvalContext ctx, Object... __) { if (ctx.engine.hasHelpers) return; print("Adding helpers"); ctx.engine.hasHelpers = true; gazelle_addHelperTablesToRules(ctx.engine); gazelle_addVarSplittersToRules(ctx.engine, __); gazelle_addVarDiscriminators(ctx.engine, __); gazelle_addVarConvertersToRules(ctx.engine, __); gazelle_addCalculationFunctionsToRules(ctx.engine, __); gazelle_addRespondToHumanOnlyHelpers(ctx.engine, __); gazelle_addForbiddenBindingHelpers(ctx.engine, __); } public static Object[] litparams(Object... l) { int n = 0, n1 = l(l); for (int i = 0; i < n1; i += 2) if (l[i] != null && l[i + 1] != null) ++n; if (n == 0) return null; Object[] params = new Object[n * 2]; int j = 0; for (int i = 0; i < n1; i += 2) { Object key = l[i], value = l[i + 1]; if (key != null && value != null) { params[j++] = key; params[j++] = value; } } return params; } public static List dm_gazelle_getChildren(GazelleTree tree, Object... __) { return gazelle_getChildren(tree, paramsPlus(__, "makeEvalContext", "dm_gazelle_stdEvalContext")); } public static Map gazelle_inputMapFromLineAndHistory(String line, List history) { Map inputMap = litmap("standard", line); for (int i = 0; i < l(history); i++) inputMap.put("history-" + (l(history) - i), history.get(i)); return inputMap; } public static List listPlus(Collection l, A... more) { return concatLists(l, asList(more)); } public static TreeMap asTreeMap(Map map) { return map instanceof TreeMap ? (TreeMap) map : new TreeMap(map); } public static void dm_gazelle_matchAdditionalInput3(List l, Map inputsByType, Object... __) { for (GazelleTree t : l) if (t.rule() != null) { RuleEngine2_MatchedRule mr = t.mr; List insWithType = t.rule().insWithType; while (licensed()) { int iCond = t.mr.iCond; TextAndType next = get(insWithType, iCond); if (next == null || !startsWith(next.type, "history-")) break; if (ai_ruleEngine2_matchStep(t.mr, inputsByType, true, __)) { print("Input match OK. new map: " + t.mr.map + ". Updating prediction."); gazelle_addPredictionToTreeNode(t); } else { print("Input match failed"); break; } } } } public static String optCurly(String s) { return curlyBraceOptIfMoreThanOneToken(s); } public static void gazelle_sortChildren(GazelleTree tree) { if (tree == null) return; gazelle_sortChildren(tree.children); } public static void gazelle_sortChildren(List children) { if (children != null) sortByCalculatedFieldDesc(children, new F1() { public Integer get(GazelleTree c) { try { return ai_goodBadToInt(c.prediction); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ai_goodBadToInt(c.prediction)"; } }); } public static void dm_gazelle_matchStatements_v2(List l, Object... __) { boolean debug = boolPar("debug", __) || boolPar("matchStatementsDebug", __); for (GazelleTree t : l) { if (t.rule() == null) continue; RuleEngine2_MatchedRule mr = t.mr; List in = t.rule().in; int iCond = t.mr.iCond; if (debug) print("matchStatements: iCond=" + iCond + " in " + in); if (iCond >= l(in)) continue; List conditions = dropFirst(iCond, in); if (debug) print("Remaining conditions for " + t.ruleID() + " with " + t.mr.map + ": " + conditions); Matches m = new Matches(); if (!matchAny("in " + (iCond + 1) + " = statement *", t.rule().comments, m)) continue; String subRuleID = m.unq(0); if (debug) print("Found subrule: " + subRuleID); List fulfillments = dm_gazelle_fulfillmentsForRule(subRuleID); Lowest> bestMap = new Lowest(); if (debug) print("Have " + n2(fulfillments, "fulfillment") + "."); for (Object f : fulfillments) { Map varMap = asCIMap(safeUnstructMap(getString("varMap", f))); if (debug) print("fulfillment => " + sfu(varMap)); boolean selfVarsFix = boolPar("selfVarsFix", __, true); if (selfVarsFix) { String cond = first(conditions); for (String x : identifiersOnly(codeTokens(mr.tokenize(cond)))) if (!varMap.containsKey(x)) { if (debug) print("Self-linking " + x); varMap.put(x, x); } } if (debug) print("Original map: " + t.mr.map); Map newMap = mergeMapsStrictlyIC(asCIMap(t.mr.map), varMap); if (newMap == null) { if (debug) printIndent("Can't merge maps"); continue; } if (debug) printIndent("Maps merged! => " + sfu(newMap)); newMap = ciMapWithoutKeysEqualToValues(newMap); if (debug) printIndent("Map simplified => " + sfu(newMap)); { if (gazelle_isRecentlyUsedMapping(t, newMap, __)) continue; } bestMap.put(newMap, l(newMap)); } Map newMap = bestMap.get(); if (newMap == null) { if (debug) print("No matching statement found"); continue; } t.mr.map = newMap; t.mr.iCond++; t.mr.remainingConditions = dropFirst(t.mr.remainingConditions); t.mr.remainingConditionsWithType = dropFirst(t.mr.remainingConditionsWithType); t.mr.out = null; t.line = t.mr.outText(); if (debug) print("Rewrote " + t.mr.rule.out + " to: " + t.line); break; } } public static Object[] passParams(Object[] __, String... params) { Map map = paramsToMap(__); List l = new ArrayList(); int n = l(l) - 1; for (String key : params) if (map.containsKey(key)) { l.add(key); l.add(map.get(key)); } return empty(l) ? null : toObjectArray(l); } public static void gazelle_dropMatchedDefaultRules(List l, Object... __) { List l2 = filter(l, t -> !eqic(t.lineType, "temporary fact")); Set trumpedRules = new HashSet(); for (GazelleTree t : l2) addAll(trumpedRules, matchAll_first("trumps rule *", t.ruleComments())); List trumped = filter(l2, new F1() { public Boolean get(GazelleTree t) { try { return contains(t.ruleComments(), "default") || trumpedRules.contains(t.ruleID()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "contains(t.ruleComments(), \"default\")\r\n || trumpedRules.contains(t.ruleID())"; } }); if (nempty(trumped) && l(trumped) < l(l2)) { if (boolPar("debug", __) || boolPar("debugDefaults", __)) { print("Removing default/trumped rules:"); printIndentLines(trumped); print("Because there are also:"); printIndentLines(listMinusSet(l2, trumped)); } l.removeAll(trumped); } } public static Map mapPlus(Map m, Object... data) { m = cloneMap(m); litmap_impl(m, data); return m; } public static Object[] assertEvenLength(Object[] a) { assertTrue(even(l(a))); return a; } public static LinkedHashMap paramsToOrderedMap(Object... params) { return asLinkedHashMap(paramsToMap(params)); } public static Object[] mapToParams(Map map) { return mapToObjectArray(map); } public static List collectField(Collection c, String field) { List l = new ArrayList(); if (c != null) for (Object a : c) l.add(getOpt(a, field)); return l; } public static List collectField(String field, Collection c) { return collectField(c, field); } public static A printIndent(A o) { print(indentx(str(o))); return o; } public static A printIndent(String indent, A o) { print(indentx(indent, str(o))); return o; } public static void printIndent(int indent, Object o) { print(indentx(indent, str(o))); } public static Map> javaTokNPunctuationWithBrackets_cache = synchronizedMRUCache(1000); public static List javaTokNPunctuationWithBrackets(String s) { List tok = javaTokNPunctuationWithBrackets_cache.get(s); if (tok == null) javaTokNPunctuationWithBrackets_cache.put(s, tok = javaTokNPunctuationWithBrackets_uncached(s)); return tok; } public static List javaTokNPunctuationWithBrackets_uncached(String s) { return tok_combineRoundOrCurlyBrackets_keep(javaTokNPunctuation_bracketsInC(s)); } public static List javaTokNoQuotes(String s) { return quotelessJavaTok(s); } public static List javaTokNoQuotesWithBrackets(String s) { return tok_combineRoundOrCurlyBrackets_keep(javaTokNoQuotes(s)); } public static String getStackTrace2(Throwable e) { return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n"); } public static String className(Object o) { return getClassName(o); } public static boolean eqOneOf(Object o, Object... l) { for (Object x : l) if (eq(o, x)) return true; return false; } public static class getOpt_Map extends WeakHashMap { public getOpt_Map() { if (getOpt_special == null) getOpt_special = new HashMap(); clear(); } public void clear() { super.clear(); put(Class.class, getOpt_special); put(String.class, getOpt_special); } } public static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map())); public static HashMap getOpt_special; public 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 Map) return ((Map) o).get(field); } Field f = map.get(field); if (f != null) return f.get(o); if (o instanceof DynamicObject) return ((DynamicObject) o).fieldValues.get(field); return null; } catch (Exception __e) { throw rethrow(__e); } } public static HashMap getOpt_makeCache(Class c) { HashMap map; if (isSubtypeOf(c, Map.class)) map = getOpt_special; else { map = new HashMap(); Class _c = c; do { for (Field f : _c.getDeclaredFields()) { f.setAccessible(true); 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; } public static List _registerWeakMap_preList; public static A _registerWeakMap(A map) { if (javax() == null) { 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; } public static void _onLoad_registerWeakMap() { assertNotNull(javax()); if (_registerWeakMap_preList == null) return; for (Object o : _registerWeakMap_preList) _registerWeakMap(o); _registerWeakMap_preList = null; } public static Map synchroMap() { return synchroHashMap(); } public static Map synchroMap(Map map) { return Collections.synchronizedMap(map); } public static int isAndroid_flag; public static boolean isAndroid() { if (isAndroid_flag == 0) isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1; return isAndroid_flag > 0; } public static void assertTrue(Object o) { if (!(eq(o, true))) throw fail(str(o)); } public static boolean assertTrue(String msg, boolean b) { if (!b) throw fail(msg); return b; } public static boolean assertTrue(boolean b) { if (!b) throw fail("oops"); return b; } public static volatile boolean licensed_yes = true; public static boolean licensed() { if (!licensed_yes) return false; ping_okInCleanUp(); return true; } public static void licensed_off() { licensed_yes = false; } public static Object call_cached(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.findMethod(method, args); if (me == null) throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found"); if ((me.getModifiers() & Modifier.STATIC) == 0) throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not static"); return invokeMethod(me, null, args); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(method, args); if (me == null) throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found"); return invokeMethod(me, o, args); } } catch (Exception __e) { throw rethrow(__e); } } public static Map emptyMap() { return new HashMap(); } public static boolean endsWith(String a, String b) { return a != null && a.endsWith(b); } public static boolean endsWith(String a, char c) { return nempty(a) && lastChar(a) == c; } public static boolean endsWith(String a, String b, Matches m) { if (!endsWith(a, b)) return false; m.m = new String[] { dropLast(l(b), a) }; return true; } public static boolean matchStartX(String pat, String s, Matches matches) { return matchStart(dropSuffix("...", pat), s, matches); } public static boolean matchEndX(String pat, String s, Matches matches) { return matchEnd(dropPrefix("...", pat), s, matches); } public static Object dm_requireAndCallModule(String moduleLibID, String method, Object... args) { return dm_callModule(dm_requireModule(moduleLibID), method, args); } public static boolean structContainsAnonymousClasses(String s) { Pattern p = compileRegexp("\\$\\d"); Producer it = javaTokC_noMLS_iterator(s); String t; while ((t = it.next()) != null) if (isIdentifier(s) && regexpContains(p, t)) return true; return false; } public static Object unstruct(String text) { return unstructure(text); } public static void mapPut(Map map, A key, B value) { if (map != null && key != null && value != null) map.put(key, value); } public static Object callAndMake(String functionName, Object... args) { return callAndMake_orDirect(functionName, args); } public static List codeTokens(List tok) { return codeTokensOnly(tok); } public static String format(String pat, Object... args) { return format3(pat, args); } public static String quote(Object o) { if (o == null) return "null"; return quote(str(o)); } public 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(); } public 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('"'); } public static List concatLists(Collection... lists) { List l = new ArrayList(); if (lists != null) for (Collection list : lists) if (list != null) l.addAll(list); return l; } public static List concatLists(Collection> lists) { List l = new ArrayList(); if (lists != null) for (Collection list : lists) if (list != null) l.addAll(list); return l; } public static List _registerDangerousWeakMap_preList; public static A _registerDangerousWeakMap(A map) { return _registerDangerousWeakMap(map, null); } public 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) { if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList(); _registerDangerousWeakMap_preList.add(pair(map, init)); return map; } call(javax(), "_registerDangerousWeakMap", map, init); return map; } public static void _onLoad_registerDangerousWeakMap() { assertNotNull(javax()); if (_registerDangerousWeakMap_preList == null) return; for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b); _registerDangerousWeakMap_preList = null; } public static List classNames(Collection l) { return getClassNames(l); } public static List classNames(Object[] l) { return getClassNames(Arrays.asList(l)); } public static Class mc() { return main.class; } public 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); } public static void multiMapPut(MultiMap mm, A key, B value) { if (mm != null && key != null && value != null) mm.put(key, value); } public static Throwable getExceptionCause(Throwable e) { Throwable c = e.getCause(); return c != null ? c : e; } public static String joinWithSpace(Collection c) { return join(" ", c); } public static String joinWithSpace(String... c) { return join(" ", c); } public 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); } public static boolean isCISet(Iterable l) { return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator(); } public static TreeSet caseInsensitiveSet() { return new TreeSet(caseInsensitiveComparator()); } public static TreeSet caseInsensitiveSet(Collection c) { return toCaseInsensitiveSet(c); } public static void addAll(Collection c, Iterable b) { if (c != null && b != null) for (A a : b) c.add(a); } public static boolean addAll(Collection c, Collection b) { return c != null && b != null && c.addAll(b); } public static boolean addAll(Collection c, B... b) { return c != null && c.addAll(Arrays.asList(b)); } public static List uniquifyList(Collection l) { if (l == null) return null; if (l(l) < 2) return asList(l); HashSet set = new HashSet(); List out = new ArrayList(); for (A a : l) if (set.add(a)) out.add(a); return out; } public static int max(int a, int b) { return Math.max(a, b); } public static int max(int a, int b, int c) { return max(max(a, b), c); } public static long max(int a, long b) { return Math.max((long) a, b); } public static long max(long a, long b) { return Math.max(a, b); } public static double max(int a, double b) { return Math.max((double) a, b); } public static float max(float a, float b) { return Math.max(a, b); } public static double max(double a, double b) { return Math.max(a, b); } public static int max(Collection c) { int x = Integer.MIN_VALUE; for (int i : c) x = max(x, i); return x; } public 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; } public 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; } public static byte max(byte[] c) { byte x = -128; for (byte d : c) if (d > x) x = d; return x; } public static short max(short[] c) { short x = -0x8000; for (short d : c) if (d > x) x = d; return x; } public static int max(int[] c) { int x = Integer.MIN_VALUE; for (int d : c) if (d > x) x = d; return x; } public static Producer javaTokC_noMLS_iterator(final String s) { return javaTokC_noMLS_iterator(s, 0); } public static Producer javaTokC_noMLS_iterator(final String s, final int startIndex) { return new Producer() { public final int l = s.length(); public int i = startIndex; public String next() { if (i >= l) return null; int j = i; char c, d; 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; } i = j; if (i >= l) return null; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else ++j; String t = quickSubstring(s, i, j); i = j; return t; } }; } public static Producer javaTokC_noMLS_onReader(final BufferedReader r) { final class X implements Producer { public StringBuilder buf = new StringBuilder(); public char c, d, e = 'x'; public X() { nc(); nc(); nc(); } public void nc() { try { c = d; d = e; if (e == '\0') return; int i = r.read(); e = i < 0 ? '\0' : i == '\0' ? '_' : (char) i; } catch (Exception __e) { throw rethrow(__e); } } public void ncSave() { if (c != '\0') { buf.append(c); nc(); } } public String next() { while (c != '\0') { if (c == ' ' || c == '\t' || c == '\r' || c == '\n') nc(); else if (c == '/' && d == '*') { do nc(); while (c != '\0' && !(c == '*' && d == '/')); nc(); nc(); } else if (c == '/' && d == '/') { do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0); } else break; } if (c == '\0') return null; if (c == '\'' || c == '"') { char opener = c; ncSave(); while (c != '\0') { if (c == opener || c == '\n') { ncSave(); break; } else if (c == '\\') { ncSave(); ncSave(); } else ncSave(); } } else if (Character.isJavaIdentifierStart(c)) do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\''); else if (Character.isDigit(c)) { do ncSave(); while (Character.isDigit(c)); if (c == 'L') ncSave(); } else ncSave(); String t = buf.toString(); buf.setLength(0); return t; } } return new X(); } public static Object _defaultClassFinder_value; public static Object _defaultClassFinder() { return _defaultClassFinder_value; } public static String unquoteUsingCharArray(String s, char[] buf) { if (s == null) return null; if (startsWith(s, '[')) { int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; if (i < s.length() && s.charAt(i) == '[') { String m = s.substring(1, i); if (s.endsWith("]" + m + "]")) return s.substring(i + 1, s.length() - i - 1); } } if (s.length() > 1) { char c = s.charAt(0); if (c == '\"' || c == '\'') { int l = endsWith(s, c) ? s.length() - 1 : s.length(); if (l > buf.length) return unquote(s); int n = 0; for (int i = 1; i < l; i++) { char ch = s.charAt(i); if (ch == '\\') { char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1); if (nextChar >= '0' && nextChar <= '7') { String code = "" + nextChar; i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; } } buf[n++] = (char) Integer.parseInt(code, 8); continue; } switch(nextChar) { case '\"': ch = '\"'; break; case '\\': ch = '\\'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case '\'': ch = '\''; break; case 'u': if (i >= l - 5) { ch = 'u'; break; } int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16); char[] x = Character.toChars(code); int lx = x.length; for (int j = 0; j < lx; j++) buf[n++] = x[j]; i += 5; continue; default: ch = nextChar; } i++; } buf[n++] = ch; } return new String(buf, 0, n); } } return s; } public static boolean structure_isMarker(String s, int i, int j) { if (i >= j) return false; if (s.charAt(i) != 'm') return false; ++i; while (i < j) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } public static String internIfLongerThan(String s, int l) { return s == null ? null : l(s) >= l ? intern(s) : s; } public static String unquote(String s) { if (s == null) return null; if (startsWith(s, '[')) { int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; if (i < s.length() && s.charAt(i) == '[') { String m = s.substring(1, i); if (s.endsWith("]" + m + "]")) return s.substring(i + 1, s.length() - i - 1); } } if (s.length() > 1) { char c = s.charAt(0); if (c == '\"' || c == '\'') { int l = endsWith(s, c) ? s.length() - 1 : s.length(); StringBuilder sb = new StringBuilder(l - 1); for (int i = 1; i < l; i++) { char ch = s.charAt(i); if (ch == '\\') { char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1); if (nextChar >= '0' && nextChar <= '7') { String code = "" + nextChar; i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; } } sb.append((char) Integer.parseInt(code, 8)); continue; } switch(nextChar) { case '\"': ch = '\"'; break; case '\\': ch = '\\'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case '\'': ch = '\''; break; case 'u': if (i >= l - 5) { ch = 'u'; break; } int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16); sb.append(Character.toChars(code)); i += 5; continue; default: ch = nextChar; } i++; } sb.append(ch); } return sb.toString(); } } return s; } public static char unquoteCharacter(String s) { assertTrue(s.startsWith("'") && s.length() > 1); return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length() - 1 : s.length()) + "\"").charAt(0); } public static double parseDouble(String s) { return Double.parseDouble(s); } public static float parseFloat(String s) { return Float.parseFloat(s); } public static boolean isLongConstant(String s) { if (!s.endsWith("L")) return false; s = s.substring(0, l(s) - 1); return isInteger(s); } public static long parseLong(String s) { if (s == null) return 0; return Long.parseLong(dropSuffix("L", s)); } public static long parseLong(Object s) { return Long.parseLong((String) s); } public static boolean isInteger(String s) { int n = l(s); if (n == 0) return false; int i = 0; if (s.charAt(0) == '-') if (++i >= n) return false; while (i < n) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } public static TreeMap ciMap() { return caseInsensitiveMap(); } public static SortedMap synchronizedTreeMap() { return synchroTreeMap(); } public static List parseList(String s) { return (List) safeUnstructure(s); } public static Map synchronizedMap() { return synchroMap(); } public static Map synchronizedMap(Map map) { return synchroMap(map); } public static byte[] hexToBytes(String s) { if (odd(l(s))) throw fail("Hex string has odd length: " + quote(shorten(10, s))); int n = l(s) / 2; byte[] bytes = new byte[n]; for (int i = 0; i < n; i++) { int a = parseHexChar(s.charAt(i * 2)); int b = parseHexChar(s.charAt(i * 2 + 1)); if (a < 0 || b < 0) throw fail("Bad hex byte: " + quote(substring(s, i * 2, i * 2 + 2)) + " at " + i * 2 + "/" + l(s)); bytes[i] = (byte) ((a << 4) | b); } return bytes; } public static boolean[] boolArrayFromBytes(byte[] a, int n) { boolean[] b = new boolean[n]; int m = min(n, l(a) * 8); for (int i = 0; i < m; i++) b[i] = (a[i / 8] & 1 << (i & 7)) != 0; return b; } public static boolean isJavaIdentifier(String s) { if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0))) return false; for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i))) return false; return true; } public static String assertIdentifier(String s) { return assertIsIdentifier(s); } public static HashMap findClass_fullName_cache = new HashMap(); public static Class findClass_fullName(String name) { synchronized (findClass_fullName_cache) { if (findClass_fullName_cache.containsKey(name)) return findClass_fullName_cache.get(name); Class c; try { c = Class.forName(name); } catch (ClassNotFoundException e) { c = null; } findClass_fullName_cache.put(name, c); return c; } } public static A nuStubInnerObject(Class c) { return nuStubInnerObject(c, null); } public static A nuStubInnerObject(Class c, Object classFinder) { try { Class outerType = getOuterClass(c, classFinder); Constructor m = c.getDeclaredConstructor(outerType); m.setAccessible(true); return (A) m.newInstance(new Object[] { null }); } catch (Exception __e) { throw rethrow(__e); } } public static Map nuEmptyObject_cache = newDangerousWeakHashMap(); public static A nuEmptyObject(Class c) { try { Constructor ctr; synchronized (nuEmptyObject_cache) { ctr = nuEmptyObject_cache.get(c); if (ctr == null) { nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c)); ctr.setAccessible(true); } } try { return (A) ctr.newInstance(); } catch (InstantiationException e) { if (empty(e.getMessage())) if ((c.getModifiers() & Modifier.ABSTRACT) != 0) throw fail("Can't instantiate abstract class " + className(c), e); else throw fail("Can't instantiate " + className(c), e); else throw rethrow(e); } } catch (Exception __e) { throw rethrow(__e); } } public static Constructor nuEmptyObject_findConstructor(Class c) { for (Constructor m : c.getDeclaredConstructors()) if (m.getParameterTypes().length == 0) return m; throw fail("No default constructor declared in " + c.getName()); } public static HashMap findClass_cache = new HashMap(); public static Class findClass(String name) { synchronized (findClass_cache) { if (findClass_cache.containsKey(name)) return findClass_cache.get(name); if (!isJavaIdentifier(name)) return null; Class c; try { c = Class.forName("main$" + name); } catch (ClassNotFoundException e) { c = null; } findClass_cache.put(name, c); return c; } } public static void setOptAllDyn(DynamicObject o, Map fields) { if (fields == null) return; HashMap fieldMap = instanceFieldsMap(o); for (Map.Entry e : fields.entrySet()) { String field = e.getKey(); Object val = e.getValue(); boolean has = fieldMap.containsKey(field); if (has) setOpt(o, field, val); else { o.fieldValues.put(intern(field), val); } } } public static void setOptAll_pcall(Object o, Map fields) { if (fields == null) return; for (String field : keys(fields)) try { setOpt(o, field, fields.get(field)); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } public static void setOptAll_pcall(Object o, Object... values) { warnIfOddCount(values); for (int i = 0; i + 1 < l(values); i += 2) { String field = (String) values[i]; Object value = values[i + 1]; try { setOpt(o, field, value); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } } public static String intern(String s) { return fastIntern(s); } public static void pcallOpt_noArgs(Object o, String method) { try { callOpt_noArgs(o, method); } catch (Throwable __e) { _handleException(__e); } } public static int[] toIntArray(List l) { int[] a = new int[l(l)]; for (int i = 0; i < a.length; i++) a[i] = l.get(i); return a; } public static TreeSet ciSet() { return caseInsensitiveSet(); } public static boolean jmatch(String pat, String s) { return jmatch(pat, s, null); } public static boolean jmatch(String pat, String s, Matches matches) { if (s == null) return false; return jmatch(pat, javaTok(s), matches); } public static boolean jmatch(String pat, List toks) { return jmatch(pat, toks, null); } public static boolean jmatch(String pat, List toks, Matches matches) { List tokpat = javaTok(pat); String[] m = match2(tokpat, toks); if (m == null) return false; else { if (matches != null) matches.m = m; return true; } } public static boolean warn_on = true; public static void warn(String s) { if (warn_on) print("Warning: " + s); } public static void warn(String s, List warnings) { warn(s); if (warnings != null) warnings.add(s); } public static Map classForName_cache = synchroHashMap(); public static Class classForName(String name) { try { Class c = classForName_cache.get(name); if (c == null) classForName_cache.put(name, c = Class.forName(name)); return c; } catch (Exception __e) { throw rethrow(__e); } } public static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap(); public static Object nuObjectWithoutArguments(String className) { try { return nuObjectWithoutArguments(classForName(className)); } catch (Exception __e) { throw rethrow(__e); } } public static A nuObjectWithoutArguments(Class c) { try { if (nuObjectWithoutArguments_cache == null) return (A) nuObjectWithoutArguments_findConstructor(c).newInstance(); Constructor m = nuObjectWithoutArguments_cache.get(c); if (m == null) nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c)); return (A) m.newInstance(); } catch (Exception __e) { throw rethrow(__e); } } public static Constructor nuObjectWithoutArguments_findConstructor(Class c) { for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) { m.setAccessible(true); return m; } throw fail("No default constructor found in " + c.getName()); } public static List getClasses(Object[] array) { List l = new ArrayList(); for (Object o : array) l.add(_getClass(o)); return l; } public static void failIfOddCount(Object... list) { if (odd(l(list))) throw fail("Odd list size: " + list); } public static boolean boolOptParam(ThreadLocal tl) { return isTrue(optPar(tl)); } public static boolean boolOptParam(Object[] __, String name) { return isTrue(optParam(__, name)); } public static boolean boolOptParam(String name, Object[] __) { return boolOptParam(__, name); } public static boolean contains(Collection c, Object o) { return c != null && c.contains(o); } public static boolean contains(Object[] x, Object o) { if (x != null) for (Object a : x) if (eq(a, o)) return true; return false; } public static boolean contains(String s, char c) { return s != null && s.indexOf(c) >= 0; } public static boolean contains(String s, String b) { return s != null && s.indexOf(b) >= 0; } public static boolean contains(BitSet bs, int i) { return bs != null && bs.get(i); } public static int indexOf(List l, A a, int startIndex) { if (l == null) return -1; for (int i = startIndex; i < l(l); i++) if (eq(l.get(i), a)) return i; return -1; } public static int indexOf(List l, int startIndex, A a) { return indexOf(l, a, startIndex); } public static int indexOf(List l, A a) { if (l == null) return -1; return l.indexOf(a); } public static int indexOf(String a, String b) { return a == null || b == null ? -1 : a.indexOf(b); } public static int indexOf(String a, String b, int i) { return a == null || b == null ? -1 : a.indexOf(b, i); } public static int indexOf(String a, char b) { return a == null ? -1 : a.indexOf(b); } public static int indexOf(String a, int i, char b) { return indexOf(a, b, i); } public static int indexOf(String a, char b, int i) { return a == null ? -1 : a.indexOf(b, i); } public static int indexOf(String a, int i, String b) { return a == null || b == null ? -1 : a.indexOf(b, i); } public static int indexOf(A[] x, A a) { if (x == null) return -1; for (int i = 0; i < l(x); i++) if (eq(x[i], a)) return i; return -1; } public static String defaultThreadName_name; public static String defaultThreadName() { if (defaultThreadName_name == null) defaultThreadName_name = "A thread by " + programID(); return defaultThreadName_name; } public static Runnable wrapAsActivity(Object r) { return toRunnable(r); } public static Thread newThread(Object runnable) { return new Thread(_topLevelErrorHandling(toRunnable(runnable))); } public static Thread newThread(Object runnable, String name) { if (name == null) name = defaultThreadName(); return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name); } public static Thread newThread(String name, Object runnable) { return newThread(runnable, name); } public static Runnable toRunnable(final Object o) { if (o instanceof Runnable) return (Runnable) o; return new Runnable() { public void run() { try { callF(o); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; } }; } public static Map _registerThread_threads; public static Object _onRegisterThread; public static Thread _registerThread(Thread t) { if (_registerThread_threads == null) _registerThread_threads = newWeakHashMap(); _registerThread_threads.put(t, true); vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc())); callF(_onRegisterThread, t); return t; } public static void _registerThread() { _registerThread(Thread.currentThread()); } public static Object pcallF(Object f, Object... args) { return pcallFunction(f, args); } public static A pcallF(F0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { return null; } } public static B pcallF(F1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { return null; } } public static int loadPage_defaultTimeout = 60000; public static ThreadLocal loadPage_charset = new ThreadLocal(); public static boolean loadPage_allowGzip = true, loadPage_debug; public static boolean loadPage_anonymous; public static int loadPage_verboseness = 100000; public static int loadPage_retries = 1; public static ThreadLocal loadPage_silent = new ThreadLocal(); public static volatile int loadPage_forcedTimeout; public static ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal(); public static ThreadLocal>> loadPage_responseHeaders = new ThreadLocal(); public static ThreadLocal> loadPage_extraHeaders = new ThreadLocal(); public static String loadPageSilently(String url) { try { return loadPageSilently(new URL(loadPage_preprocess(url))); } catch (Exception __e) { throw rethrow(__e); } } public static String loadPageSilently(URL url) { try { if (url.getProtocol().equals("https")) disableCertificateValidation(); if (!networkAllowanceTest(str(url))) throw fail("Not allowed: " + url); IOException e = null; for (int tries = 0; tries < loadPage_retries; tries++) try { URLConnection con = loadPage_openConnection(url); return loadPage(con, url); } catch (IOException _e) { e = _e; if (loadPageThroughProxy_enabled) { print("Trying proxy because of: " + e); try { return loadPageThroughProxy(str(url)); } catch (Throwable e2) { print(" " + exceptionToStringShort(e2)); } } else if (loadPage_debug) print(exceptionToStringShort(e)); if (tries < loadPage_retries - 1) sleepSeconds(1); } throw e; } catch (Exception __e) { throw rethrow(__e); } } public static String loadPage_preprocess(String url) { if (url.startsWith("tb/")) url = tb_mainServer() + "/" + url; if (url.indexOf("://") < 0) url = "http://" + url; return url; } public static String loadPage(String url) { try { url = loadPage_preprocess(url); if (!isTrue(loadPage_silent.get())) printWithTime("Loading: " + hideCredentials(url)); return loadPageSilently(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } public static String loadPage(URL url) { return loadPage(url.toExternalForm()); } public static String loadPage(URLConnection con, URL url) throws IOException { return loadPage(con, url, true); } public static String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException { Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders); if (addHeaders) try { if (!loadPage_anonymous) setHeaders(con); if (loadPage_allowGzip) con.setRequestProperty("Accept-Encoding", "gzip"); con.setRequestProperty("X-No-Cookies", "1"); for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key)); } catch (Throwable e) { } vm_generalSubMap("URLConnection per thread").put(currentThread(), con); loadPage_responseHeaders.set(con.getHeaderFields()); InputStream in = null; try { in = con.getInputStream(); if (loadPage_debug) print("Put stream in map: " + currentThread()); String contentType = con.getContentType(); if (contentType == null) { throw new IOException("Page could not be read: " + hideCredentials(url)); } String charset = loadPage_charset == null ? null : loadPage_charset.get(); if (charset == null) charset = loadPage_guessCharset(contentType); if ("gzip".equals(con.getContentEncoding())) { if (loadPage_debug) print("loadPage: Using gzip."); in = newGZIPInputStream(in); } Reader r; try { r = new InputStreamReader(in, unquote(charset)); } catch (UnsupportedEncodingException e) { print(toHex(utf8(charset))); throw e; } StringBuilder buf = new StringBuilder(); int n = 0; while (true) { int ch = r.read(); if (ch < 0) break; buf.append((char) ch); ++n; if ((n % loadPage_verboseness) == 0) print(" " + n + " chars read"); } return buf.toString(); } finally { if (loadPage_debug) print("loadPage done"); vm_generalSubMap("URLConnection per thread").remove(currentThread()); if (in != null) in.close(); } } public static String loadPage_guessCharset(String contentType) { Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType); String match = m.matches() ? m.group(1) : null; if (loadPage_debug) print("loadPage: contentType=" + contentType + ", match: " + match); return or(match, "UTF-8"); } public static URLConnection loadPage_openConnection(URL url) { URLConnection con = openConnection(url); int timeout = toInt(loadPage_forcedTimeout_byThread.get()); if (timeout == 0) timeout = loadPage_forcedTimeout; if (timeout != 0) setURLConnectionTimeouts(con, loadPage_forcedTimeout); else setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout); return con; } public static URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) { con.setConnectTimeout(toInt(timeout)); con.setReadTimeout(toInt(timeout)); if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout) print("Warning: Timeouts not set by JDK."); return con; } public static long parseSnippetID(String snippetID) { long id = Long.parseLong(shortenSnippetID(snippetID)); if (id == 0) throw fail("0 is not a snippet ID"); return id; } public static String formatSnippetIDOpt(String s) { return isSnippetID(s) ? formatSnippetID(s) : s; } public static String formatSnippetID(String id) { return "#" + parseSnippetID(id); } public static String formatSnippetID(long id) { return "#" + id; } public static Class getMainClass() { return mc(); } public static Class getMainClass(Object o) { try { if (o == null) return null; if (o instanceof Class && eq(((Class) o).getName(), "x30")) return (Class) o; return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main"); } catch (Exception __e) { throw rethrow(__e); } } public static File newFile(File base, String... names) { for (String name : names) base = new File(base, name); return base; } public static File newFile(String name) { return name == null ? null : new File(name); } public static void _close(AutoCloseable c) { if (c != null) try { c.close(); } catch (Throwable e) { if (c instanceof javax.imageio.stream.ImageOutputStream) return; else throw rethrow(e); } } public static String loadGZTextFile(File file) { try { if (!file.isFile()) return null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream fis = new FileInputStream(file); GZIPInputStream gis = newGZIPInputStream(fis); try { byte[] buffer = new byte[1024]; int len; while ((len = gis.read(buffer)) != -1) { baos.write(buffer, 0, len); } } finally { fis.close(); } baos.close(); return fromUtf8(baos.toByteArray()); } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFile(String fileName) { return loadTextFile(fileName, null); } public static String loadTextFile(File f, String defaultContents) { try { checkFileNotTooBigToRead(f); if (f == null || !f.exists()) return defaultContents; FileInputStream fileInputStream = new FileInputStream(f); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); return loadTextFile(inputStreamReader); } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFile(File fileName) { return loadTextFile(fileName, null); } public static String loadTextFile(String fileName, String defaultContents) { return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents); } public static String loadTextFile(Reader reader) throws IOException { StringBuilder builder = new StringBuilder(); try { char[] buffer = new char[1024]; int n; while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n); } finally { reader.close(); } return str(builder); } public static File getCodeProgramDir() { return getCodeProgramDir(getProgramID()); } public static File getCodeProgramDir(String snippetID) { return new File(javaxCodeDir(), formatSnippetID(snippetID)); } public static File getCodeProgramDir(long snippetID) { return getCodeProgramDir(formatSnippetID(snippetID)); } public static A printHidingCredentials(A o) { print(hideCredentials(str(o))); return o; } public static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); } public static String hideCredentials(String url) { return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2="); } public static String hideCredentials(Object o) { return hideCredentials(str(o)); } public static void logQuotedWithDate(String s) { logQuotedWithTime(s); } public static void logQuotedWithDate(String logFile, String s) { logQuotedWithTime(logFile, s); } public static void logQuotedWithDate(File logFile, String s) { logQuotedWithTime(logFile, s); } public static File infoBoxesLogFile() { return new File(javaxDataDir(), "Logs/infoBoxes.txt"); } public static JWindow showWindow(Component c) { JWindow w = new JWindow(); w.add(wrap(c)); return w; } public static JPanel infoMessage_makePanel(String text) { final JTextArea ta = wrappedTextArea(text); onClick(ta, new Runnable() { public void run() { try { disposeWindow(ta); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disposeWindow(ta)"; } }); int size = 14; if (l(text) <= 50) size *= 2; else if (l(text) < 100) size = iround(size * 1.5); ta.setFont(typeWriterFont(size)); JScrollPane sp = jscroll(ta); return withMargin(sp); } public static int moveToTopRightCorner_inset = 20; public static A moveToTopRightCorner(A a) { return moveToTopRightCorner(moveToTopRightCorner_inset, moveToTopRightCorner_inset, a); } public static A moveToTopRightCorner(int insetX, int insetY, A a) { Window w = getWindow(a); if (w != null) w.setLocation(getScreenSize().width - w.getWidth() - insetX, insetY); return a; } public static A disposeWindowAfter(int delay, final A w) { if (w != null) swingLater(delay, new Runnable() { public void run() { try { w.dispose(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "w.dispose();"; } }); return w; } public static A disposeWindowAfter(A w, double seconds) { return disposeWindowAfter(toMS_int(seconds), w); } public static int iround(double d) { return (int) Math.round(d); } public static int iround(Number n) { return iround(toDouble(n)); } public static Throwable printStackTrace(Throwable e) { print(getStackTrace(e)); return e; } public static void printStackTrace() { printStackTrace(new Throwable()); } public static void printStackTrace(String msg) { printStackTrace(new Throwable(msg)); } public static String exceptionToStringShort(Throwable e) { lastException(e); e = getInnerException(e); String msg = hideCredentials(unnull(e.getMessage())); if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0) return baseClassName(e) + prependIfNempty(": ", msg); else return msg; } public static Lock downloadLock_lock = fairLock(); public static Lock downloadLock() { return downloadLock_lock; } public static void lock(Lock lock) { try { ping(); if (lock == null) return; try { lock.lockInterruptibly(); } catch (InterruptedException e) { print("Locking interrupted! I probably deadlocked, oops."); printStackTrace(e); rethrow(e); } ping(); } catch (Exception __e) { throw rethrow(__e); } } public static void lock(Lock lock, String msg) { print("Locking: " + msg); lock(lock); } public static void lock(Lock lock, String msg, long timeout) { print("Locking: " + msg); lockOrFail(lock, timeout); } public static ReentrantLock lock() { return fairLock(); } public static String getSnippetTitleOpt(String s) { return isSnippetID(s) ? getSnippetTitle(s) : s; } public static void unlock(Lock lock, String msg) { if (lock == null) return; print("Unlocking: " + msg); lock.unlock(); } public static void unlock(Lock lock) { if (lock == null) return; lock.unlock(); } public static boolean isQuoted(String s) { if (isNormalQuoted(s)) return true; return isMultilineQuoted(s); } 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)); } public static String join(Iterable strings) { return join("", strings); } public static String join(Iterable strings, String glue) { return join(glue, strings); } public static String join(String[] strings) { return join("", strings); } public static String join(String glue, Pair p) { return p == null ? "" : str(p.a) + glue + str(p.b); } public static String[] toStringArray(Collection c) { String[] a = new String[l(c)]; Iterator it = c.iterator(); for (int i = 0; i < l(a); i++) a[i] = it.next(); return a; } public static String[] toStringArray(Object o) { if (o instanceof String[]) return (String[]) o; else if (o instanceof Collection) return toStringArray((Collection) o); else throw fail("Not a collection or array: " + getClassName(o)); } public static void assertFalse(Object o) { if (!(eq(o, false))) throw fail(str(o)); } public static boolean assertFalse(boolean b) { if (b) throw fail("oops"); return b; } public static boolean assertFalse(String msg, boolean b) { if (b) throw fail(msg); return b; } public static Component frameIcon(Component c, String imageID) { setFrameIconLater(c, imageID); return c; } public static Component frameIcon(String imageID, Component c) { setFrameIconLater(c, imageID); return c; } public static String or2(String a, String b) { return nempty(a) ? a : b; } public static String or2(String a, String b, String c) { return or2(or2(a, b), c); } public static String javaxDefaultIcon() { return "#1005557"; } public static void setOptMC(String field, Object value) { setOpt(mc(), field, value); } public static A centerFrame(A c) { Window w = getWindow(c); if (w != null) w.setLocationRelativeTo(null); return c; } public static A centerFrame(int w, int h, A c) { return centerFrame(setFrameSize(w, h, c)); } public static A setFrameSize(A c, int w, int h) { JFrame f = getFrame(c); if (f != null) f.setSize(w, h); return c; } public static A setFrameSize(int w, int h, A c) { return setFrameSize(c, w, h); } public static float getSwingFontScale() { return or((Float) vm_generalMap_get("swingFontScale_value"), 1f); } public static Object callOpt(Object o) { return callF(o); } public static A callOpt(Object o, String method, Object... args) { return (A) callOpt_cached(o, method, args); } public static Object getConsoleTextArea_gen() { return getOpt(get(getJavaX(), "console"), "textArea"); } public static JTextField consoleInputField() { Object console = get(getJavaX(), "console"); return (JTextField) getOpt(console, "tfInput"); } public static void revalidateFrame(Component c) { revalidate(getFrame(c)); } public static String hopeningTag(String tag, Map params) { return hopeningTag(tag, mapToParams(params)); } public static String hopeningTag(String tag, Object... params) { StringBuilder buf = new StringBuilder(); buf.append("<" + tag); for (int i = 0; i < l(params); i += 2) { String name = (String) get(params, i); Object val = get(params, i + 1); if (nempty(name) && val != null) { if (val == html_valueLessParam()) buf.append(" " + name); else { String s = str(val); if (!empty(s)) buf.append(" " + name + "=" + htmlQuote(s)); } } } buf.append(">"); return str(buf); } public static boolean neqic(String a, String b) { return !eqic(a, b); } public static String[] dropLast(String[] a, int n) { n = Math.min(n, a.length); String[] b = new String[a.length - n]; System.arraycopy(a, 0, b, 0, b.length); return b; } public static List dropLast(List l) { return subList(l, 0, l(l) - 1); } public static List dropLast(int n, List l) { return subList(l, 0, l(l) - n); } public static List dropLast(Iterable l) { return dropLast(asList(l)); } public static String dropLast(String s) { return substring(s, 0, l(s) - 1); } public static String dropLast(String s, int n) { return substring(s, 0, l(s) - n); } public static String dropLast(int n, String s) { return dropLast(s, n); } public static Runnable addThreadInfoToRunnable(final Object r) { final Object info = _threadInfo(); return info == null ? asRunnable(r) : new Runnable() { public void run() { try { _inheritThreadInfo(info); callF(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_inheritThreadInfo(info); callF(r);"; } }; } public static JFrame getFrame(final Object _o) { return swing(new F0() { public JFrame get() { try { Object o = _o; if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o)); if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof JFrame) return (JFrame) c; c = c.getParent(); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; } }); } public static Class javax() { return getJavaX(); } public static boolean isCIMap(Map m) { return m instanceof TreeMap && ((TreeMap) m).comparator() == caseInsensitiveComparator(); } public static A liftLast(List l) { if (l.isEmpty()) return null; int i = l(l) - 1; A a = l.get(i); l.remove(i); return a; } public static int smartLastIndexOf(String s, char c) { if (s == null) return 0; int i = s.lastIndexOf(c); return i >= 0 ? i : l(s); } public static String trimSubstring(String s, int x) { return trim(substring(s, x)); } public static String trimSubstring(String s, int x, int y) { return trim(substring(s, x, y)); } public static String rtrim_fromLines(Collection lines) { StringBuilder buf = new StringBuilder(); if (lines != null) { boolean first = true; for (Object line : lines) { if (first) first = false; else buf.append('\n'); buf.append(str(line)); } } return buf.toString(); } public static CloseableIterableIterator linesFromFile(File f) { try { if (!f.exists()) return emptyCloseableIterableIterator(); if (ewic(f.getName(), ".gz")) return linesFromReader(utf8bufferedReader(newGZIPInputStream(f))); return linesFromReader(utf8bufferedReader(f)); } catch (Exception __e) { throw rethrow(__e); } } public static boolean containsIgnoreCase(Collection l, String s) { if (l != null) for (String x : l) if (eqic(x, s)) return true; return false; } public static boolean containsIgnoreCase(String[] l, String s) { if (l != null) for (String x : l) if (eqic(x, s)) return true; return false; } public static boolean containsIgnoreCase(String s, char c) { return indexOfIgnoreCase(s, String.valueOf(c)) >= 0; } public static boolean containsIgnoreCase(String a, String b) { return indexOfIgnoreCase(a, b) >= 0; } public static Map> parse3_cachedInput_cache = synchronizedMRUCache(1000); public static List parse3_cachedInput(String s) { List tok = parse3_cachedInput_cache.get(s); if (tok == null) parse3_cachedInput_cache.put(s, tok = parse3(s)); return tok; } public static Map> parse3_cachedPattern_cache = synchronizedMRUCache(1000); public static synchronized List parse3_cachedPattern(String s) { List tok = parse3_cachedPattern_cache.get(s); if (tok == null) parse3_cachedPattern_cache.put(s, tok = parse3(s)); return tok; } public static String[] match2(List pat, List tok) { int i = pat.indexOf("..."); if (i < 0) return match2_match(pat, tok); pat = new ArrayList(pat); pat.set(i, "*"); while (pat.size() < tok.size()) { pat.add(i, "*"); pat.add(i + 1, ""); } return match2_match(pat, tok); } public static String[] match2_match(List pat, List tok) { List result = new ArrayList(); if (pat.size() != tok.size()) { return null; } for (int i = 1; i < pat.size(); i += 2) { String p = pat.get(i), t = tok.get(i); if (eq(p, "*")) result.add(t); else if (!equalsIgnoreCase(unquote(p), unquote(t))) return null; } return result.toArray(new String[result.size()]); } public static List javaTokWithBrackets(String s) { return javaTokPlusBrackets(s); } public static Pair listToPair(List l) { return l(l) != 2 ? null : pair(first(l), second(l)); } public static List splitAtDoubleArrow(String s) { return splitAtDoubleArrow(javaTok(s)); } public static List splitAtDoubleArrow(List tok) { List l = new ArrayList(); int i = 0; while (i < l(tok)) { int j = indexOfSubList(tok, ll("=", "", ">"), i); if (i >= l(tok)) break; if (j < 0) j = l(tok); l.add(trimJoin(tok.subList(i, j))); i = j + 3; } return l; } public static String asString(Object o) { return o == null ? null : o.toString(); } public static Throwable getInnerException(Throwable e) { if (e == null) return null; while (e.getCause() != null) e = e.getCause(); return e; } public static Throwable getInnerException(Runnable r) { return getInnerException(getException(r)); } public static A assertEquals(Object x, A y) { return assertEquals(null, x, y); } public static A assertEquals(String msg, Object x, A y) { if (assertVerbose()) return assertEqualsVerbose(msg, x, y); if (!(x == null ? y == null : x.equals(y))) throw fail((msg != null ? msg + ": " : "") + y + " != " + x); return y; } public static List javaTokC(String s) { if (s == null) return null; int l = s.length(); ArrayList tok = new ArrayList(); int i = 0; while (i < l) { int j = i; char c, d; 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; } i = j; if (i >= l) break; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } 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)); i = j; } return tok; } public static void quoteToPrintWriter(String s, PrintWriter out) { if (s == null) { out.print("null"); return; } out.print('"'); int l = s.length(); for (int i = 0; i < l; i++) { char c = s.charAt(i); if (c == '\\' || c == '"') { out.print('\\'); out.print(c); } else if (c == '\r') out.print("\\r"); else if (c == '\n') out.print("\\n"); else if (c == '\0') out.print("\\0"); else out.print(c); } out.print('"'); } public static String quoteCharacter(char c) { if (c == '\'') return "'\\''"; if (c == '\\') return "'\\\\'"; if (c == '\r') return "'\\r'"; if (c == '\n') return "'\\n'"; if (c == '\t') return "'\\t'"; return "'" + c + "'"; } public static int shorten_default = 100; public static String shorten(String s) { return shorten(s, shorten_default); } public static String shorten(String s, int max) { return shorten(s, max, "..."); } public static String shorten(String s, int max, String shortener) { if (s == null) return ""; if (max < 0) return s; return s.length() <= max ? s : substring(s, 0, min(s.length(), max - l(shortener))) + shortener; } public static String shorten(int max, String s) { return shorten(s, max); } public static boolean isCISet_gen(Iterable l) { return l instanceof TreeSet && className(((TreeSet) l).comparator()).contains("CIComp"); } public static boolean isCIMap_gen(Map map) { return map instanceof TreeMap && className(((TreeMap) map).comparator()).contains("CIComp"); } public static String boolArrayToHex(boolean[] a) { return bytesToHex(boolArrayToBytes(a)); } public static Iterator emptyIterator() { return Collections.emptyIterator(); } public static String shortDynamicClassName(Object o) { if (o instanceof DynamicObject && ((DynamicObject) o).className != null) return ((DynamicObject) o).className; return shortClassName(o); } public static int stdcompare(Number a, Number b) { return cmp(a, b); } public static int stdcompare(String a, String b) { return cmp(a, b); } public static int stdcompare(long a, long b) { return a < b ? -1 : a > b ? 1 : 0; } public static int stdcompare(Object a, Object b) { return cmp(a, b); } public static Map getDeclaredFields_cache = newDangerousWeakHashMap(); public static Field[] getDeclaredFields_cached(Class c) { Field[] fields; synchronized (getDeclaredFields_cache) { fields = getDeclaredFields_cache.get(c); if (fields == null) { getDeclaredFields_cache.put(c, fields = c.getDeclaredFields()); for (Field f : fields) f.setAccessible(true); } } return fields; } public static boolean startsWithDigit(String s) { return nempty(s) && isDigit(s.charAt(0)); } public static List mapToLines(Map map) { List l = new ArrayList(); for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key))); return l; } public static String mapToLines(Map map, Object f) { return lines(map(map, f)); } public static String beautifyStructure(String s) { List tok = javaTok(s); structure_addTokenMarkers(tok); jreplace(tok, "lhm", ""); return join(tok); } public static boolean even(int i) { return (i & 1) == 0; } public static boolean even(long i) { return (i & 1) == 0; } public static boolean startsWithIgnoreCase(String a, String b) { return regionMatchesIC(a, 0, b, 0, b.length()); } public static int min(int a, int b) { return Math.min(a, b); } public static long min(long a, long b) { return Math.min(a, b); } public static float min(float a, float b) { return Math.min(a, b); } public static float min(float a, float b, float c) { return min(min(a, b), c); } public static double min(double a, double b) { return Math.min(a, b); } public static double min(double[] c) { double x = Double.MAX_VALUE; for (double d : c) x = Math.min(x, d); return x; } public static float min(float[] c) { float x = Float.MAX_VALUE; for (float d : c) x = Math.min(x, d); return x; } public static byte min(byte[] c) { byte x = 127; for (byte d : c) if (d < x) x = d; return x; } public static short min(short[] c) { short x = 0x7FFF; for (short d : c) if (d < x) x = d; return x; } public static int min(int[] c) { int x = Integer.MAX_VALUE; for (int d : c) if (d < x) x = d; return x; } public static A shallowClone(A o) { return (A) shallowClone_impl(o); } public static Object shallowClone_impl(Object o) { if (o == null) return o; if (o instanceof List) return cloneList((List) o); if (o instanceof Map) return cloneMap(((Map) o)); if (o instanceof String || o instanceof Number || o instanceof Boolean) return o; if (o instanceof Object[]) { Object[] l = (Object[]) o; return l.clone(); } Class c = o.getClass(); final Object clone = nuEmptyObject(c); copyFields(o, clone); return clone; } public static A assertNotNull(A a) { assertTrue(a != null); return a; } public static A assertNotNull(String msg, A a) { assertTrue(msg, a != null); return a; } public static Collection gazelle_executeSplitterRule(RuleEngine2 engine, RuleEngine2.SimplifyWithRule rule, String input) { Object f = rule.function(); Collection out = (Collection) ((f instanceof String ? callF(engine.callFunctionOnString, (String) f, input) : callF(f, input))); if (l(out) == 1 && eq(first(out), input)) return emptyList(); return out; } public static String joinWithVBar(Iterable l) { return join(" | ", l); } public static Object[] litobjectarray(Object... l) { return litObjectArray(l); } public static List sortByMethodDesc(Collection c, final String method) { return sortByCalculatedFieldDesc(c, new F1() { public Object get(A a) { try { return callOpt(a, method); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callOpt(a, method)"; } }); } public static List sortByMethodDesc(String method, Collection c) { return sortByMethodDesc(c, method); } public static List ai_ruleEngine2_rulesForInput_5(RuleEngine2 engine, Map inputsByType, Object... __) { boolean debug = boolPar("debug", __); List l = new ArrayList(); for (RuleEngine2.Rule rule : engine.rules) { if (rule instanceof RuleEngine2.SimplifyWithRule) { if (((RuleEngine2.SimplifyWithRule) rule).isSplitRule) continue; String in = inputsByType.get("standard"); Object f = ((RuleEngine2.SimplifyWithRule) rule).function(); if (debug) print("Running simplifier " + ((RuleEngine2.SimplifyWithRule) rule).globalID + ": " + f); Object arg = ((RuleEngine2.SimplifyWithRule) rule).callOnTree ? optPar("tree", __) : in; if (arg == null) continue; Object result = f instanceof String ? arg instanceof String ? callF(engine.callFunctionOnString, (String) f, arg) : callAndMake((String) f, arg) : callF(f, arg); if (result == null) continue; List list = result instanceof Collection ? allToString((Collection) result) : ll(str(result)); if (debug) print("Simplifier returned: " + list); theLoop: for (String x : list) { if (nempty(x) && neq(x, in)) { final RuleEngine2_MatchedRule matched = new RuleEngine2_MatchedRule(); matched.rule = ((RuleEngine2.SimplifyWithRule) rule); matched.out = x; matched.inputsByType = inputsByType; for (Object massager : unnull(matched.rule.mapMassagers)) if (callF(massager, new HashMap(), null, null, matched) == null) { if (debug) print("mapMassager returned null: " + massager); continue theLoop; } l.add(matched); } } continue; } final RuleEngine2_MatchedRule matched = new RuleEngine2_MatchedRule(); matched.rule = rule; matched.inputsByType = inputsByType; matched.map = ciMap(); matched.tokenizationFunction = or(matchAny_firstGroup("tokenize with *", rule.comments), "javaTokNPunctuationWithBrackets"); matched.outTokenizer = matchAny_firstGroup("tokenize out with *", rule.comments); if (!ai_ruleEngine2_matchStep(matched, inputsByType, true, __)) continue; l.add(matched); } return l; } public static List ai_ruleEngine2_rulesForInput_5_allConditions(RuleEngine2 engine, Map inputsByType, Object... __) { List notDone = ai_ruleEngine2_rulesForInput_5(engine, inputsByType, __); List done = new ArrayList(); boolean debug = boolPar("debug", __); while (nempty(notDone)) { List l = notDone; notDone = new ArrayList(); for (RuleEngine2_MatchedRule mr : l) { if (!mr.moreConditions()) { if (debug) print("Done: " + mr.ruleID()); done.add(mr); } else { if (debug) print("Matching step " + mr.iCond + " in " + mr.ruleID()); if (ai_ruleEngine2_matchStep(mr, inputsByType, false)) { if (debug) print("Step succeeded"); notDone.add(mr); } else done.add(mr); } } } return done; } public static void gazelle_addPredictionToTreeNode(GazelleTree child, Object... __) { boolean debug = boolPar("debug", __); Set badComments = (Set) (optPar("badComments", __)); Set acceptablePurposes = (Set) (optPar("acceptablePurposes", __)); RuleEngine2_MatchedRule r = child.mr; GazelleEvalContext ctx = child.ctx; if (containsAny(r.rule.comments, badComments) || acceptablePurposes != null && !acceptablePurposes.contains(unnull(r.rule.purpose))) { if (debug) print("prediction=bad for various reasons"); child.prediction = "bad"; } else { if (ctx.predictor == null) child.prediction = null; else { child.prediction = ctx.predictor.get(ctx, r); if (debug) print("Prediction=" + child.prediction + " for " + r + " (" + (r.moreConditions() ? "unsatisfied" : "satisfied") + ") by " + ctx.predictor); } } } public static List antiFilter(Iterable c, Object pred) { if (pred instanceof F1) return antiFilter(c, (F1) pred); List x = new ArrayList(); if (c != null) for (Object o : c) if (!isTrue(callF(pred, o))) x.add(o); return x; } public static List antiFilter(Object pred, Iterable c) { return antiFilter(c, pred); } public static List antiFilter(Object pred, Object[] c) { return antiFilter(pred, wrapArrayAsList(c)); } public static List antiFilter(Iterable c, F1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (!pred.get(o).booleanValue()) x.add(o); return x; } public static List antiFilter(F1 pred, Iterable c) { return antiFilter(c, pred); } public static List antiFilter(Iterable c, IF1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (!pred.get(o).booleanValue()) x.add(o); return x; } public static List antiFilter(IF1 pred, Iterable c) { return antiFilter(c, pred); } public static void printStructure(String prefix, Object o) { if (endsWithLetter(prefix)) prefix += ": "; print(prefix + structureForUser(o)); } public static void printStructure(Object o) { print(structureForUser(o)); } public static boolean eqicOneOf(String s, String... l) { for (String x : l) if (eqic(s, x)) return true; return false; } public static class gazelle_addHelperTablesToRules_Massager { public List> helperTable; public Map> helperIndex; public gazelle_addHelperTablesToRules_Massager() { } public gazelle_addHelperTablesToRules_Massager(List> helperTable, Map> helperIndex) { this.helperIndex = helperIndex; this.helperTable = helperTable; } public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) { if (map == null) return null; for (String t : codeTokens(matched.tokenize(matched.rule.out))) { if (map.containsKey(t)) continue; Pair idx = helperIndex.get(t); if (idx == null) continue; { final Map __429 = cloneMap(map); for (String key : keys(__429)) { String val = __429.get(key); int idx2 = indexOfIC(helperTable.get(idx.a), key); if (idx2 < 0) continue; Pair idxVal = helperIndex.get(val); if (idxVal == null) continue; String out = _get(_get(helperTable, idxVal.a), idx.b); print("Massaged: " + t + " <-> " + key + " => " + out); mapPut(map, t, out); } } } return map; } } public static void gazelle_addHelperTablesToRules(RuleEngine2 engine) { Matches m = new Matches(); for (final RuleEngine2.Rule r : engine.rules) { { if (!(matchAny("use helper table mech list *", r.comments, m))) continue; } List entries = mL(m.unq(0)); { if (empty(entries)) continue; } final List> helperTable = map("tok_splitAtCommaOrDoubleArrow", entries); final Map> helperIndex = indexTwoDArrayIC(helperTable); r.addMapMassager(new gazelle_addHelperTablesToRules_Massager(helperTable, helperIndex)); } } public static class gazelle_addVarSplittersToRules_VarSplitter { public String var; public boolean debug; public gazelle_addVarSplittersToRules_VarSplitter() { } public gazelle_addVarSplittersToRules_VarSplitter(String var, boolean debug) { this.debug = debug; this.var = var; } public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) { if (map == null) return null; String value = getOrKeep(map, curly(var)); List tok1 = matched.tokenize(var); List tok2 = matched.tokenize(uncurly(value)); if (debug) print("VarSplitter: " + tok1 + " / " + tok2); if (l(tok1) != l(tok2)) return null; int oldSize = l(map); for (int i = 1; i < l(tok1); i += 2) if (!strictPutIC(map, tok1.get(i), tok2.get(i))) return null; if (debug) print("VarSplitter done => " + map); matched.nPossibleVars = matched.nPossibleVars() + l(map) - oldSize; return map; } } public static void gazelle_addVarSplittersToRules(RuleEngine2 engine, Object... __) { Matches m = new Matches(); boolean debug = boolPar("debug", __); for (final RuleEngine2.Rule r : engine.rules) { { if (!(jmatchAny("split *", r.comments, m) && isQuoted(m.get(0)))) continue; } String var = m.unq(0); if (debug) print("Made splitter for: " + var); r.addMapMassager(new gazelle_addVarSplittersToRules_VarSplitter(var, debug)); } } public static class gazelle_addVarDiscriminators_VarDiscriminator { public String var; public Object discriminator; public boolean debug; public gazelle_addVarDiscriminators_VarDiscriminator() { } public gazelle_addVarDiscriminators_VarDiscriminator(String var, Object discriminator, boolean debug) { this.debug = debug; this.discriminator = discriminator; this.var = var; } public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) { if (map == null) return null; String value = map.get(var); if (value != null && !isTrue(callAndMake_orF1(discriminator, value))) { if (debug) print("Rejecting var: " + var + " -> " + value + " because of " + discriminator); return null; } return map; } } public static void gazelle_addVarDiscriminators(RuleEngine2 engine, Object... __) { boolean debug = boolPar("debug", __); for (final RuleEngine2.Rule r : engine.rules) for (Matches m : getJMatches_all("var * should satisfy *", r.comments)) { String var = m.unq(0), discriminator = m.unq(1); if (debug) print("Made discriminator for: " + var); r.addMapMassager(new gazelle_addVarDiscriminators_VarDiscriminator(var, discriminator, debug)); } } public static class gazelle_addVarConvertersToRules_VarConverter { public String var1, var2; public Object converter; public boolean debug; public gazelle_addVarConvertersToRules_VarConverter() { } public gazelle_addVarConvertersToRules_VarConverter(String var1, String var2, Object converter, boolean debug) { this.debug = debug; this.converter = converter; this.var2 = var2; this.var1 = var1; } public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) { if (map == null) return null; String value = map.get(var1); if (value == null) return map; String value2 = (String) callAndMake_orF1(converter, value); if (debug) print("VarConverter: " + value + " => " + value2); if (!strictPutIC(map, var2, value2)) return null; return map; } } public static void gazelle_addVarConvertersToRules(RuleEngine2 engine, Object... __) { boolean debug = boolPar("debug", __) || boolPar("varConverterDebug", __); for (final RuleEngine2.Rule r : engine.rules) for (Matches m : getJMatches_all("convert var * to * with *", r.comments)) r.addMapMassager(new gazelle_addVarConvertersToRules_VarConverter(m.unq(0), m.unq(1), m.unq(2), debug)); } public static class gazelle_addCalculationFunctionsToRules_Calculator { public String var1, var2, var3; public Object function; public boolean debug; public gazelle_addCalculationFunctionsToRules_Calculator() { } public gazelle_addCalculationFunctionsToRules_Calculator(String var1, String var2, String var3, Object function, boolean debug) { this.debug = debug; this.function = function; this.var3 = var3; this.var2 = var2; this.var1 = var1; } public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) { if (map == null) return null; double result; try { String value1 = getOrKeep(map, var1), value2 = getOrKeep(map, var2); result = (double) callAndMake_orF2(function, parseDouble(value1), parseDouble(value2)); } catch (Throwable _e) { return null; } if (!strictPutIC(map, var3, str(iround(result)))) return null; return map; } } public static void gazelle_addCalculationFunctionsToRules(RuleEngine2 engine, Object... __) { boolean debug = boolPar("debug", __) || boolPar("calcDebug", __); for (final RuleEngine2.Rule r : engine.rules) for (Matches m : getJMatches_all("compute var * from * and * using *", r.comments)) { r.addMapMassager(new gazelle_addCalculationFunctionsToRules_Calculator(m.unq(1), m.unq(2), m.unq(0), m.unq(3), debug)); if (debug) print("Calculator made"); } } public static class gazelle_addRespondToHumanOnlyHelpers_Check { public boolean debug; public gazelle_addRespondToHumanOnlyHelpers_Check() { } public gazelle_addRespondToHumanOnlyHelpers_Check(boolean debug) { this.debug = debug; } public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) { if (map == null) return null; if (debug) print("humanOnlyHelper for " + matched.ruleID() + ": " + matched.inputsByType); if (!eq("true", matched.inputsByType.get("_respondingToHuman"))) return null; return map; } } public static void gazelle_addRespondToHumanOnlyHelpers(RuleEngine2 engine, Object... __) { boolean debug = boolPar("debug", __) || boolPar("humanOnlyDebug", __); for (final RuleEngine2.Rule r : engine.rules) if (cic(r.comments, "only answer to human")) { if (debug) print("Made human-only helper"); r.addMapMassager(new gazelle_addRespondToHumanOnlyHelpers_Check(debug)); } } public static class gazelle_addForbiddenBindingHelpers_Blocker { public String var, value; public boolean debug; public gazelle_addForbiddenBindingHelpers_Blocker() { } public gazelle_addForbiddenBindingHelpers_Blocker(String var, String value, boolean debug) { this.debug = debug; this.value = value; this.var = var; } public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) { if (map == null) return null; if (value == null) { if (map.containsKey(var)) return null; } else if (eqic(value, map.get(var))) return null; return map; } } public static class gazelle_addForbiddenBindingHelpers_TotalBlocker { public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) { if (nempty(map)) return null; return map; } } public static void gazelle_addForbiddenBindingHelpers(RuleEngine2 engine, Object... __) { boolean debug = boolPar("debug", __) || boolPar("forbiddenBindingsDebug", __); for (final RuleEngine2.Rule r : engine.rules) { for (Matches m : getJMatches_all("don't change * to *", r.comments)) r.addMapMassager(new gazelle_addForbiddenBindingHelpers_Blocker(m.unq(0), m.unq(1), debug)); for (Matches m : getJMatches_all("don't change *", r.comments)) if (isQuoted(m.get(0))) r.addMapMassager(new gazelle_addForbiddenBindingHelpers_Blocker(m.unq(0), null, debug)); if (cic(r.comments, "don't change anything")) r.addMapMassager(new gazelle_addForbiddenBindingHelpers_TotalBlocker()); } } public static boolean ai_ruleEngine2_matchStep(final RuleEngine2_MatchedRule matched, Map inputsByType, boolean fillRemainingConditions, Object... __) { boolean debug = boolPar("debug", __); RuleEngine2.Rule rule = matched.rule; TextAndType in = rule.insWithType.get(matched.iCond); String input = inputsByType.get(in.type); if (input == null) return false; Object inputMassager = get(rule.inputMassagers, matched.iCond); Object checkerFunction = get(rule.checkerFunctions, matched.iCond); Object matcher = get(rule.matchers, matched.iCond); List tokC = null, tokI = null; Map map; if (inputMassager != null) { input = (String) callF(inputMassager, input); if (debug) print("Massaged input to: " + input); if (input == null) return false; } if (checkerFunction != null) map = (Map) callF(checkerFunction, input); else { String cond = in.text; String tokenize = matched.tokenizationFunction; tokC = (List) callAndMake(tokenize, cond); tokI = (List) callAndMake(tokenize, input); if (debug) print("matchStep inputsByType=" + sfu(asTreeMap(inputsByType))); if (debug) print("matchStep in=" + in + ", iCond=" + matched.iCond + ", insWithType: " + rule.insWithType); if (debug) print("matchStep tokI/tokC: " + codeTokens(tokI) + " / " + codeTokens(tokC)); if (contains(cond, "{}")) tokI = ai_applyWordSplitPattern1(tokC, tokI); if (matcher != null) map = (Map) callF(matcher, tokC, tokI, matched); else map = zipTwoListsToCIMap_strict_withoutEquals(tokC, tokI); } if (debug) print("matchStep for rule " + rule.globalID + " map: " + map); if (!gazelle_addMatch(matched, map, tokC, tokI, __)) { if (debug) print("addMatch failed - " + strWithIdentityHashCode(matched)); return false; } matched.iCond++; if (debug) print("matchStep succeeded. " + matched); matched.matchedLines.add(pair(tokC, tokI)); if (fillRemainingConditions) { matched.remainingConditions = nullIfEmpty(map(dropFirst(matched.iCond, rule.in), new F1() { public String get(String s) { try { return matched.applyMappingTo(s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "matched.applyMappingTo(s)"; } })); matched.remainingConditionsWithType = nullIfEmpty(map(dropFirst(matched.iCond, rule.insWithType), new F1() { public TextAndType get(TextAndType in) { try { return new TextAndType(matched.applyMappingTo(in.text), in.type); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "TextAndType(matched.applyMappingTo(in.text), in.type)"; } })); } Map, Integer> qualities = ai_ruleEngine2_mappingQualities(rule); for (String a : keys(map)) { String b = map.get(a); mapPut(matched.mappingQuality, a, qualities.get(pair(a, b))); } if (debug) print("iCond now=" + matched.iCond + ", next input: " + get(matched.rule.insWithType, matched.iCond)); return true; } public static String curlyBraceOptIfMoreThanOneToken(String s) { return !isCurlyBraced(s) && numberOfJavaTokens(s) > 1 ? curlyBrace(s) : s; } public static List sortByCalculatedFieldDesc(Collection c, final Object f) { return sortByCalculatedFieldDesc_inPlace(cloneList(c), f); } public static List sortByCalculatedFieldDesc(Object f, Collection c) { return sortByCalculatedFieldDesc(c, f); } public static int ai_goodBadToInt(String s) { if (eq(s, "good")) return 1; if (eq(s, "bad")) return -1; return 0; } public static String[] dropFirst(int n, String[] a) { return drop(n, a); } public static String[] dropFirst(String[] a) { return drop(1, a); } public static Object[] dropFirst(Object[] a) { return drop(1, a); } public static List dropFirst(List l) { return dropFirst(1, l); } public static List dropFirst(int n, Iterable i) { return dropFirst(n, toList(i)); } public static List dropFirst(Iterable i) { return dropFirst(toList(i)); } public static List dropFirst(int n, List l) { return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size())); } public static List dropFirst(List l, int n) { return dropFirst(n, l); } public static String dropFirst(int n, String s) { return substring(s, n); } public static String dropFirst(String s) { return substring(s, 1); } public static boolean matchAny(Collection patterns, String s, Matches m) { for (String pattern : patterns) if (match(pattern, s, m)) return true; return false; } public static boolean matchAny(Collection patterns, String s) { return matchAny(patterns, s, null); } public static boolean matchAny(String pat, Iterable l) { return matchAny(pat, l, null); } public static boolean matchAny(String pat, Iterable l, Matches m) { if (l != null) for (String s : l) if (match(pat, s, m)) return true; return false; } public static Map safeUnstructMap(String s) { return safeUnstructureMap(s); } public static List identifiersOnly(Collection l) { List out = new ArrayList(); for (String a : unnull(l)) if (isIdentifier(a)) out.add(a); return out; } public static Map mergeMapsStrictlyIC(Map map1, Map map2) { if (map2 == null) return map1; if (map1 == null) return map2; if (!canPutAllStrictlyIC(map1, map2)) return null; return mergeMaps(map1, map2); } public static Map ciMapWithoutKeysEqualToValues(Map map) { if (map == null) return null; Map map2 = ciMap(); for (String key : keys(map)) { String value = map.get(key); if (!eqic(key, value)) map2.put(key, value); } return map2; } public static boolean gazelle_isRecentlyUsedMapping(GazelleTree t, Map varMap, Object... __) { String context = stringPar("context", __); if (empty(context)) return false; return t != null && t.rule() != null && t.rule().avoidRecentlyUsedMappings && isTrue(dm_call(gazelle_rumCRUD(), "hasRecentlyUsedMapping", context, t.rule().globalID, varMap)); } public static Map paramsToMap(Object... params) { int n = l(params); if (l(params) == 1 && params[0] instanceof Map) return (Map) params[0]; LinkedHashMap map = new LinkedHashMap(); for (int i = 0; i + 1 < n; i += 2) mapPut(map, params[i], params[i + 1]); return map; } public static Object[] toObjectArray(Collection c) { List l = asList(c); return l.toArray(new Object[l.size()]); } public static List matchAll_first(String pat, Iterable l) { return map(matchAll(pat, l), new F1() { public String get(Matches m) { try { return m.get(0); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.get(0)"; } }); } public static > A printIndentLines(String indent, A lines) { return printLinesWithIndent(indent, lines); } public static > A printIndentLines(A lines) { return printLinesWithIndent(defaultIndent(), lines); } public static Map cloneMap(Map map) { if (map == null) return new HashMap(); synchronized (map) { return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map); } } public static Object[] mapToObjectArray(Map map) { List l = new ArrayList(); for (Object o : keys(map)) { l.add(o); l.add(map.get(o)); } return toObjectArray(l); } public static String indentx(String s) { return indentx(indent_default, s); } public static String indentx(int n, String s) { return dropSuffix(repeat(' ', n), indent(n, s)); } public static String indentx(String indent, String s) { return dropSuffix(indent, indent(indent, s)); } public static final Map callOpt_cache = newDangerousWeakHashMap(); public 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); 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); } } public 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; } } public static List splitAtEllipsis(String s) { return splitAtTokens(javaTokWithBrackets(s), ".", "", ".", "", "."); } public static Map synchronizedMRUCache(int maxSize) { return synchroMap(new MRUCache(maxSize)); } public static List tok_combineRoundOrCurlyBrackets_keep(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && eqOneOf(t, "{", "(")) { int j = findEndOfBracketPart(tok, i); l.add(joinSubList(tok, i, j)); i = j - 1; } else l.add(t); } return l; } public static List javaTokNPunctuation_bracketsInC(String s) { List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { int j = i; String t; char c; while (j < l(tok) && l(t = tok.get(j)) == 1 && !Character.isLetterOrDigit(c = t.charAt(0)) && "{}()".indexOf(c) < 0) j += 2; if (j > i) replaceSubList(tok, i - 1, j, ll(joinSubList(tok, i - 1, j))); } return tok; } public static List quotelessJavaTok(String s) { ArrayList tok = new ArrayList(); int l = s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c, d; 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); if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else ++j; tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } public static String getStackTrace(Throwable throwable) { lastException(throwable); return getStackTrace_noRecord(throwable); } public static String getStackTrace_noRecord(Throwable throwable) { StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); return hideCredentials(writer.toString()); } public static String getStackTrace() { return getStackTrace_noRecord(new Throwable()); } public 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; } public static String replacePrefix(String prefix, String replacement, String s) { if (!startsWith(s, prefix)) return s; return replacement + substring(s, l(prefix)); } public static Throwable innerException2(Throwable e) { if (e == null) return null; while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause(); return e; } public static void clear(Collection c) { if (c != null) c.clear(); } public static void put(Map map, A a, B b) { if (map != null) map.put(a, b); } public static boolean isSubtypeOf(Class a, Class b) { return b.isAssignableFrom(a); } public static A printException(A e) { printStackTrace(e); return e; } public static Map synchroHashMap() { return Collections.synchronizedMap(new HashMap()); } public static String joinWithComma(Collection c) { return join(", ", c); } public static String joinWithComma(String... c) { return join(", ", c); } public static String joinWithComma(Pair p) { return p == null ? "" : joinWithComma(str(p.a), str(p.b)); } public static char lastChar(String s) { return empty(s) ? '\0' : s.charAt(l(s) - 1); } public static boolean matchStart(String pat, String s) { return matchStart(pat, s, null); } public static boolean matchStart(String pat, String s, Matches matches) { if (s == null) return false; return matchStart(pat, parse3_cachedInput(s), matches); } public static boolean matchStart(String pat, List toks, Matches matches) { if (toks == null) return false; List tokpat = parse3_cachedPattern(pat); if (toks.size() < tokpat.size()) return false; String[] m = match2(tokpat, toks.subList(0, tokpat.size())); if (m == null) return false; if (matches != null) { matches.m = new String[m.length + 1]; arraycopy(m, matches.m); matches.m[m.length] = join(toks.subList(tokpat.size(), toks.size())); } return true; } public static String dropSuffix(String suffix, String s) { return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s; } public static boolean matchEnd(String pat, String s) { return matchEnd(pat, s, null); } public static boolean matchEnd(String pat, String s, Matches matches) { if (s == null) return false; List tokpat = parse3(pat), toks = parse3(s); if (toks.size() < tokpat.size()) return false; String[] m = match2(tokpat, takeLast(l(tokpat), toks)); if (m == null) return false; if (matches != null) { matches.m = new String[m.length + 1]; arraycopy(m, matches.m); matches.m[m.length] = join(dropLast(l(tokpat), toks)); } return true; } public static Object dm_callModule(Object moduleOrID, String method, Object... args) { Object mod = dm_getModule(moduleOrID); if (mod == null) return null; AutoCloseable __798 = dm_enter(mod); try { return call(mod, method, args); } finally { _close(__798); } } public static String dm_requireModule(String moduleLibID) { return dm_makeModule(moduleLibID); } public static Map compileRegexp_cache = syncMRUCache(10); public static java.util.regex.Pattern compileRegexp(String pat) { java.util.regex.Pattern p = compileRegexp_cache.get(pat); if (p == null) { compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat)); } return p; } public static boolean isIdentifier(String s) { return isJavaIdentifier(s); } public static boolean regexpContains(String pat, String s) { return regexpFinds(pat, s); } public static boolean regexpContains(Pattern pat, String s) { return regexpFinds(pat, s); } public static Object callAndMake_orDirect(String functionName, List args) { return callAndMake_orDirect(functionName, toObjectArray(args)); } public static Object callAndMake_orDirect(String functionName, Object... args) { if (functionName == null) return null; if (hasMethod(mc(), functionName, args)) return callMC(functionName, args); else return makeAndCall_cached(functionName, args); } public static List codeTokensOnly(List tok) { int n = tok.size(); List l = emptyList(n / 2); for (int i = 1; i < n; i += 2) l.add(tok.get(i)); return l; } public static String format3(String pat, Object... args) { if (args.length == 0) return pat; List tok = javaTokPlusPeriod(pat); int argidx = 0; for (int i = 1; i < tok.size(); i += 2) if (tok.get(i).equals("*")) tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null")); return join(tok); } public static String format3_formatArg(Object arg) { if (arg == null) return "null"; if (arg instanceof String) { String s = (String) arg; return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s); } if (arg instanceof Integer || arg instanceof Long) return String.valueOf(arg); return quote(structure(arg)); } public 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 Comparator caseInsensitiveComparator() { return betterCIComparator(); } public static String quickSubstring(String s, int i, int j) { if (i == j) return ""; return s.substring(i, j); } public static TreeMap caseInsensitiveMap() { return new TreeMap(caseInsensitiveComparator()); } public static NavigableMap synchroTreeMap() { return Collections.synchronizedNavigableMap(new TreeMap()); } public static Object safeUnstructure(String s) { return unstructure(s, true); } public static boolean odd(int i) { return (i & 1) != 0; } public static boolean odd(long i) { return (i & 1) != 0; } public static boolean odd(BigInteger i) { return odd(toInt(i)); } public static int parseHexChar(char c) { if (c >= '0' && c <= '9') return charDiff(c, '0'); if (c >= 'a' && c <= 'f') return charDiff(c, 'a') + 10; if (c >= 'A' && c <= 'F') return charDiff(c, 'A') + 10; return -1; } public static String assertIsIdentifier(String s) { if (!isIdentifier(s)) throw fail("Not an identifier: " + quote(s)); return s; } public static Class getOuterClass(Class c) { return getOuterClass(c, null); } public static Class getOuterClass(Class c, Object classFinder) { try { String s = c.getName(); int i = s.lastIndexOf('$'); String name = substring(s, 0, i); if (classFinder != null) return (Class) callF(classFinder, name); return Class.forName(name); } catch (Exception __e) { throw rethrow(__e); } } public static HashMap instanceFieldsMap(Object o) { Class c = o.getClass(); HashMap map; synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } return map; } public static Field setOpt_findField(Class c, String field) { HashMap map; synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } return map.get(field); } public static void setOpt(Object o, String field, Object value) { try { if (o == null) return; Class c = o.getClass(); HashMap map; if (getOpt_cache == null) map = getOpt_makeCache(c); else synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } if (map == getOpt_special) { if (o instanceof Class) { setOpt((Class) o, field, value); return; } setOpt_raw(o, field, value); return; } Field f = map.get(field); if (f != null) smartSet(f, o, value); } catch (Exception __e) { throw rethrow(__e); } } public static void setOpt(Class c, String field, Object value) { if (c == null) return; try { Field f = setOpt_findStaticField(c, field); if (f != null) smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } public static Field setOpt_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) { f.setAccessible(true); return f; } _c = _c.getSuperclass(); } while (_c != null); return null; } public static void warnIfOddCount(Object... list) { if (odd(l(list))) printStackTrace("Odd list size: " + list); } public static Method fastIntern_method; public static String fastIntern(String s) { try { if (s == null) return null; if (fastIntern_method == null) { fastIntern_method = findMethodNamed(javax(), "internPerProgram"); if (fastIntern_method == null) upgradeJavaXAndRestart(); } return (String) fastIntern_method.invoke(null, s); } catch (Exception __e) { throw rethrow(__e); } } public static Map> callOpt_noArgs_cache = newDangerousWeakHashMap(); public static Object callOpt_noArgs(Object o, String method) { try { if (o == null) return null; if (o instanceof Class) return callOpt(o, method); Class c = o.getClass(); HashMap map; synchronized (callOpt_noArgs_cache) { map = callOpt_noArgs_cache.get(c); if (map == null) map = callOpt_noArgs_makeCache(c); } Method m = map.get(method); return m != null ? m.invoke(o) : null; } catch (Exception __e) { throw rethrow(__e); } } public static HashMap callOpt_noArgs_makeCache(Class c) { HashMap map = new HashMap(); Class _c = c; do { for (Method m : c.getDeclaredMethods()) if (m.getParameterTypes().length == 0) { m.setAccessible(true); String name = m.getName(); if (!map.containsKey(name)) map.put(name, m); } _c = _c.getSuperclass(); } while (_c != null); callOpt_noArgs_cache.put(c, map); return map; } public static int javaTok_n, javaTok_elements; public static boolean javaTok_opt; public 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; 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); 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 == '\'') { ++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)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } 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; } public static List javaTok(List tok) { return javaTokWithExisting(join(tok), tok); } public static Class _getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } public static Class _getClass(Object o) { return o == null ? null : o instanceof Class ? (Class) o : o.getClass(); } public static Class _getClass(Object realm, String name) { try { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; } } public static Runnable _topLevelErrorHandling(final Runnable runnable) { final Object info = _threadInfo(); return new Runnable() { public void run() { try { try { _threadInheritInfo(info); runnable.run(); } catch (Throwable __e) { _handleException(__e); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }"; } }; } public static Map vm_generalWeakSubMap(Object name) { synchronized (get(javax(), "generalMap")) { Map map = (Map) (vm_generalMap_get(name)); if (map == null) vm_generalMap_put(name, map = newWeakMap()); return map; } } public static WeakReference weakRef(A a) { return newWeakReference(a); } public static Object pcallFunction(Object f, Object... args) { try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); } return null; } public static volatile boolean disableCertificateValidation_attempted; public static void disableCertificateValidation() { try { if (disableCertificateValidation_attempted) return; disableCertificateValidation_attempted = true; try { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); } catch (Throwable __e) { _handleException(__e); } } catch (Exception __e) { throw rethrow(__e); } } public static boolean networkAllowanceTest(String url) { return isAllowed("networkAllowanceTest", url); } public static final boolean loadPageThroughProxy_enabled = false; public static String loadPageThroughProxy(String url) { return null; } public static void sleepSeconds(double s) { if (s > 0) sleep(round(s * 1000)); } public static String tb_mainServer_default = "http://tinybrain.de:8080"; public static Object tb_mainServer_override; public static String tb_mainServer() { if (tb_mainServer_override != null) return (String) callF(tb_mainServer_override); return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default)); } public static File tb_mainServer_file() { return getProgramFile("#1001638", "mainserver.txt"); } public static boolean tb_mainServer_isDefault() { return eq(tb_mainServer(), tb_mainServer_default); } public static A printWithTime(A a) { print(hmsWithColons() + ": " + a); return a; } public static A getAndClearThreadLocal(ThreadLocal tl) { A a = tl.get(); tl.set(null); return a; } public static void setHeaders(URLConnection con) throws IOException { String computerID = getComputerID_quick(); if (computerID != null) try { con.setRequestProperty("X-ComputerID", computerID); con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version")); } catch (Throwable e) { } } public static Map vm_generalSubMap(Object name) { synchronized (get(javax(), "generalMap")) { Map map = (Map) (vm_generalMap_get(name)); if (map == null) vm_generalMap_put(name, map = synchroMap()); return map; } } public static GZIPInputStream newGZIPInputStream(File f) { return gzInputStream(f); } public static GZIPInputStream newGZIPInputStream(InputStream in) { return gzInputStream(in); } public static String toHex(byte[] bytes) { return bytesToHex(bytes); } public static String toHex(byte[] bytes, int ofs, int len) { return bytesToHex(bytes, ofs, len); } public static byte[] utf8(String s) { return toUtf8(s); } public static Matcher regexpMatcher(String pat, String s) { return compileRegexp(pat).matcher(unnull(s)); } public static URLConnection openConnection(URL url) { try { ping(); callOpt(javax(), "recordOpenURLConnection", str(url)); return url.openConnection(); } catch (Exception __e) { throw rethrow(__e); } } public static int toInt(Object o) { if (o == null) return 0; if (o instanceof Number) return ((Number) o).intValue(); if (o instanceof String) return parseInt((String) o); throw fail("woot not int: " + getClassName(o)); } public static int toInt(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } public static URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) { if (con.getConnectTimeout() == 0) { con.setConnectTimeout(toInt(timeout)); if (con.getConnectTimeout() != timeout) print("Warning: URL connect timeout not set by JDK."); } if (con.getReadTimeout() == 0) { con.setReadTimeout(toInt(timeout)); if (con.getReadTimeout() != timeout) print("Warning: URL read timeout not set by JDK."); } return con; } public static String shortenSnippetID(String snippetID) { if (snippetID.startsWith("#")) snippetID = snippetID.substring(1); String httpBlaBla = "http://tinybrain.de/"; if (snippetID.startsWith(httpBlaBla)) snippetID = snippetID.substring(httpBlaBla.length()); return "" + parseLong(snippetID); } public static boolean isSnippetID(String s) { try { parseSnippetID(s); return true; } catch (RuntimeException e) { return false; } } public static String fromUtf8(byte[] bytes) { try { return new String(bytes, "UTF-8"); } catch (Exception __e) { throw rethrow(__e); } } public static ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal(); public static void checkFileNotTooBigToRead(File f) { callF(checkFileNotTooBigToRead_tl.get(), f); } public static File javaxCodeDir_dir; public static File javaxCodeDir() { return javaxCodeDir_dir != null ? javaxCodeDir_dir : new File(userHome(), "JavaX-Code"); } public static File javaxCodeDir(String sub) { return newFile(javaxCodeDir(), sub); } public static void logQuotedWithTime(String s) { logQuotedWithTime(standardLogFile(), s); } public static void logQuotedWithTime(File logFile, String s) { logQuoted(logFile, logQuotedWithTime_format(s)); } public static void logQuotedWithTime(String logFile, String s) { logQuoted(logFile, logQuotedWithTime_format(s)); } public static String logQuotedWithTime_format(String s) { return (now()) + " " + s; } public static File javaxDataDir_dir; public static File javaxDataDir() { return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data"); } public static File javaxDataDir(String... subs) { return newFile(javaxDataDir(), subs); } public static Component wrap(Object swingable) { return _recordNewSwingComponent(wrap_2(swingable)); } public static Component wrap_2(Object swingable) { if (swingable == null) return null; Component c; if (swingable instanceof Component) c = (Component) swingable; else c = (Component) callOpt(swingable, "swing"); if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree) return jscroll(c); return c == null ? jlabel(str(swingable)) : c; } public static JTextArea wrappedTextArea(final JTextArea ta) { enableWordWrapForTextArea(ta); return ta; } public static JTextArea wrappedTextArea() { return wrappedTextArea(jtextarea()); } public static JTextArea wrappedTextArea(String text) { JTextArea ta = wrappedTextArea(); setText(ta, text); return ta; } public static A onClick(final A c, final Object runnable) { if (c != null) { swing(new Runnable() { public void run() { try { c.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { callF(runnable, e); } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(MouseEv..."; } }); } return c; } public static void onClick(JButton btn, final Object runnable) { onEnter(btn, runnable); } public static void disposeWindow(final Window window) { if (window != null) { swing(new Runnable() { public void run() { try { window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); myFrames_list.remove(window); window.dispose(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); //..."; } }); } } public static void disposeWindow(final Component c) { disposeWindow(getWindow(c)); } public static void disposeWindow(Object o) { if (o != null) disposeWindow(((Component) o)); } public static void disposeWindow() { disposeWindow(heldInstance(Component.class)); } public static JScrollPane jscroll(final Component c) { return swing(new F0() { public JScrollPane get() { try { return new JScrollPane(c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret new JScrollPane(c);"; } }); } public static int withMargin_defaultWidth = 6; public static JPanel withMargin(Component c) { return withMargin(withMargin_defaultWidth, c); } public static JPanel withMargin(int w, Component c) { return withMargin(w, w, c); } public static JPanel withMargin(int w, int h, Component c) { return withMargin(w, h, w, h, c); } public static JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right)); p.add(c); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat..."; } }); } public static Window getWindow(Object o) { if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof Window) return (Window) c; c = c.getParent(); } return null; } public static Dimension getScreenSize() { return Toolkit.getDefaultToolkit().getScreenSize(); } public static void swingLater(long delay, final Object r) { javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r))); timer.setRepeats(false); timer.start(); } public static void swingLater(Object r) { SwingUtilities.invokeLater(toRunnable(r)); } public static int toMS_int(double seconds) { return toInt_checked((long) (seconds * 1000)); } public static double toDouble(Object o) { if (o instanceof Number) return ((Number) o).doubleValue(); if (o instanceof BigInteger) return ((BigInteger) o).doubleValue(); if (o == null) return 0.0; throw fail(o); } public static volatile PersistableThrowable lastException_lastException; public static PersistableThrowable lastException() { return lastException_lastException; } public static void lastException(Throwable e) { lastException_lastException = persistableThrowable(e); } public static String baseClassName(String className) { return substring(className, className.lastIndexOf('.') + 1); } public static String baseClassName(Object o) { return baseClassName(getClassName(o)); } public static String prependIfNempty(String prefix, String s) { return empty(s) ? s : prefix + s; } public static ReentrantLock fairLock() { return new ReentrantLock(true); } public static void lockOrFail(Lock lock, long timeout) { try { ping(); if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) { String s = "Couldn't acquire lock after " + timeout + " ms."; if (lock instanceof ReentrantLock) { ReentrantLock l = (ReentrantLock) lock; s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner"); } throw fail(s); } ping(); } catch (Exception __e) { throw rethrow(__e); } } public static String getSnippetTitle(String id) { try { if (id == null) return null; if (!isSnippetID(id)) return "?"; if (isLocalSnippetID(id)) return localSnippetTitle(id); long parsedID = parseSnippetID(id); String url; if (isImageServerSnippet(parsedID)) url = imageServerURL() + "title/" + parsedID + muricaCredentialsQuery(); else if (isGeneralFileServerSnippet(parsedID)) url = "http://butter.botcompany.de:8080/files/name/" + parsedID; else url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies(); String title = trim(loadPageSilently(url)); if (title != null) try { saveTextFileIfChanged(snippetTitle_cacheFile(id), title); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } return or(title, "?"); } catch (Exception __e) { throw rethrow(__e); } } public static String getSnippetTitle(long id) { return getSnippetTitle(fsI(id)); } public static boolean isNormalQuoted(String s) { int l = l(s); if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"')) return false; int j = 1; while (j < l) if (s.charAt(j) == '"') return j == l - 1; else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; return false; } public static boolean isMultilineQuoted(String s) { if (!startsWith(s, "[")) return false; int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; return i < s.length() && s.charAt(i) == '['; } public static JFrame setFrameIconLater(Component c, final String imageID) { final JFrame frame = getFrame(c); if (frame != null) startThread("Loading Icon", new Runnable() { public void run() { try { final Image i = imageIcon(or2(imageID, "#1005557")).getImage(); swingLater(new Runnable() { public void run() { try { frame.setIconImage(i); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setIconImage(i);"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final Image i = imageIcon(or2(imageID, \"#1005557\")).getImage();\r\n swingL..."; } }); return frame; } public static Object vm_generalMap_get(Object key) { return vm_generalMap().get(key); } public static A revalidate(final A c) { if (c == null || !c.isShowing()) return c; { swing(new Runnable() { public void run() { try { c.revalidate(); c.repaint(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "// magic combo to actually relayout and repaint\r\n c.revalidate();\r\n c.r..."; } }); } return c; } public static void revalidate(RootPaneContainer c) { revalidate((Component) c); } public static void revalidate(JFrame f) { revalidate((Component) f); } public static void revalidate(JInternalFrame f) { revalidate((Component) f); } public static Object html_valueLessParam_cache; public static Object html_valueLessParam() { if (html_valueLessParam_cache == null) html_valueLessParam_cache = html_valueLessParam_load(); return html_valueLessParam_cache; } public static Object html_valueLessParam_load() { return new Object(); } public static String htmlQuote(String s) { return "\"" + htmlencode_forParams(s) + "\""; } public static List> _threadInfo_makers = synchroList(); public static Object _threadInfo() { if (empty(_threadInfo_makers)) return null; HashMap map = new HashMap(); pcallFAll(_threadInfo_makers, map); return map; } public static Runnable asRunnable(Object o) { return toRunnable(o); } public static void _inheritThreadInfo(Object info) { _threadInheritInfo(info); } public static List buttonsInGroup(ButtonGroup g) { if (g == null) return ll(); return asList(g.getElements()); } public static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; public static CloseableIterableIterator emptyCloseableIterableIterator() { return emptyCloseableIterableIterator_instance; } public static boolean ewic(String a, String b) { return endsWithIgnoreCase(a, b); } public static boolean ewic(String a, String b, Matches m) { return endsWithIgnoreCase(a, b, m); } public static CloseableIterableIterator linesFromReader(Reader r) { final BufferedReader br = bufferedReader(r); return iteratorFromFunction_f0_autoCloseable(new F0() { public String get() { try { return readLineFromReaderWithClose(br); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret readLineFromReaderWithClose(br);"; } }, _wrapIOCloseable(r)); } public static BufferedReader utf8bufferedReader(InputStream in) { try { return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in)); } catch (Exception __e) { throw rethrow(__e); } } public static BufferedReader utf8bufferedReader(File f) { try { return utf8bufferedReader(newFileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } public static int indexOfIgnoreCase(List a, String b) { return indexOfIgnoreCase(a, b, 0); } public static int indexOfIgnoreCase(List a, String b, int i) { int n = l(a); for (; i < n; i++) if (eqic(a.get(i), b)) return i; return -1; } public static int indexOfIgnoreCase(String a, String b) { return indexOfIgnoreCase_manual(a, b); } public static List parse3(String s) { return dropPunctuation(javaTokPlusPeriod(s)); } public static boolean equalsIgnoreCase(String a, String b) { return eqic(a, b); } public static boolean equalsIgnoreCase(char a, char b) { return eqic(a, b); } public static List javaTokPlusBrackets(String s) { return tok_combineRoundOrCurlyBrackets_keep(javaTok(s)); } public static A second(List l) { return get(l, 1); } public static A second(A[] bla) { return bla == null || bla.length <= 1 ? null : bla[1]; } public static B second(Pair p) { return p == null ? null : p.b; } public static B second(T3 t) { return t == null ? null : t.b; } public static int indexOfSubList(List x, List y) { return indexOfSubList(x, y, 0); } public static int indexOfSubList(List x, List y, int i) { outer: for (; i + l(y) <= l(x); i++) { for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y.get(j))) continue outer; return i; } return -1; } public static int indexOfSubList(List x, A[] y, int i) { outer: for (; i + l(y) <= l(x); i++) { for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y[j])) continue outer; return i; } return -1; } public static String trimJoin(List s) { return trim(join(s)); } public static Throwable getException(Runnable r) { try { callF(r); return null; } catch (Throwable e) { return e; } } public static ThreadLocal assertVerbose_value = new ThreadLocal(); public static void assertVerbose(boolean b) { assertVerbose_value.set(b); } public static boolean assertVerbose() { return isTrue(assertVerbose_value.get()); } public static String javaTok_substringC(String s, int i, int j) { return s.substring(i, j); } public static byte[] boolArrayToBytes(boolean[] a) { byte[] b = new byte[(l(a) + 7) / 8]; for (int i = 0; i < l(a); i++) if (a[i]) b[i / 8] |= 1 << (i & 7); return b; } public static String shortClassName(Object o) { if (o == null) return null; Class c = o instanceof Class ? (Class) o : o.getClass(); String name = c.getName(); return shortenClassName(name); } public static int cmp(Number a, Number b) { return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue()); } public static int cmp(double a, double b) { return a < b ? -1 : a == b ? 0 : 1; } public static int cmp(Object a, Object b) { if (a == null) return b == null ? 0 : -1; if (b == null) return 1; return ((Comparable) a).compareTo(b); } public static boolean isDigit(char c) { return Character.isDigit(c); } public static String structure_addTokenMarkers(String s) { return join(structure_addTokenMarkers(javaTok(s))); } public static List structure_addTokenMarkers(List tok) { TreeSet refs = new TreeSet(); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (t.startsWith("t") && isInteger(t.substring(1))) refs.add(parseInt(t.substring(1))); } if (empty(refs)) return tok; for (int i : refs) { int idx = i * 2 + 1; String t = ""; if (endsWithLetterOrDigit(tok.get(idx - 1))) t = " "; tok.set(idx, t + "m" + i + " " + tok.get(idx)); } return tok; } public static String jreplace(String s, String in, String out) { return jreplace(s, in, out, null); } public static String jreplace(String s, String in, String out, Object condition) { List tok = javaTok(s); return jreplace(tok, in, out, condition) ? join(tok) : s; } public static boolean jreplace(List tok, String in, String out) { return jreplace(tok, in, out, false, true, null); } public static boolean jreplace(List tok, String in, String out, Object condition) { return jreplace(tok, in, out, false, true, condition); } public static boolean jreplace(List tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) { String[] toks = javaTokForJFind_array(in); int lTokin = toks.length * 2 + 1; boolean anyChange = false; for (int n = 0; n < 10000; n++) { int i = findCodeTokens(tok, 1, ignoreCase, toks, condition); if (i < 0) return anyChange; List subList = tok.subList(i - 1, i + lTokin - 1); String expansion = jreplaceExpandRefs(out, subList); int end = i + lTokin - 2; clearAllTokens(tok, i, end); tok.set(i, expansion); if (reTok) reTok(tok, i, end); anyChange = true; } throw fail("woot? 10000! " + quote(in) + " => " + quote(out)); } public static boolean jreplace_debug; public static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) { return a != null && a.regionMatches(true, offsetA, b, offsetB, len); } public static A copyFields(Object x, A y, String... fields) { if (empty(fields)) { Map map = objectToMap(x); for (String field : map.keySet()) setOpt(y, field, map.get(field)); } else for (String field : fields) { Object o = getOpt(x, field); if (o != null) setOpt(y, field, o); } return y; } public static A copyFields(Object x, A y, Collection fields) { return copyFields(x, y, asStringArray(fields)); } public static Object[] litObjectArray(Object... l) { return l; } public static List allToString(Collection c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } public static List allToString(Object[] c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } public static String matchAny_firstGroup(String pat, Iterable l) { Matches m = new Matches(); return matchAny(pat, l, m) ? m.unq(0) : null; } public static List wrapArrayAsList(A[] a) { return a == null ? null : Arrays.asList(a); } public static boolean endsWithLetter(String s) { return nempty(s) && isLetter(last(s)); } public static int indexOfIC(List a, String b) { return indexOfIgnoreCase(a, b); } public static int indexOfIC(List a, String b, int i) { return indexOfIgnoreCase(a, b, i); } public static int indexOfIC(String a, String b) { return indexOfIgnoreCase(a, b); } public static A _get(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } public static Object _get(Object o, String field) { return get(o, field); } public static Object _get(String field, Object o) { return get(o, field); } public static A _get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } public static List mL(String name) { return mechList_opt(name); } public static List tok_splitAtCommaOrDoubleArrow(String s) { return tok_splitAtCommaOrDoubleArrow(javaTok(s)); } public static List tok_splitAtCommaOrDoubleArrow(List tok) { List l = splitAtDoubleArrow(tok); if (l(l) > 1) return l; return tok_splitAtComma(tok); } public static Map> indexTwoDArrayIC(List> table) { if (table == null) return null; Map> map = ciMap(); for (int i = 0; i < l(table); i++) { List row = table.get(i); for (int j = 0; j < l(row); j++) map.put(row.get(j), pair(i, j)); } return map; } public static A getOrKeep(Map map, A a) { if (map == null) return a; A v = map.get(a); return v != null ? v : a; } public static String curly(String s) { return optionalCurlyBrace(s); } public static String uncurly(String s) { return tok_unCurlyBracket(s); } public static boolean strictPutIC(Map map, A key, String value) { if (!(map != null && key != null && value != null)) return true; String old = map.get(key); if (old == null) { map.put(key, value); return true; } return eqic(old, value); } public static boolean jmatchAny(String pat, Iterable l) { return jmatch_any(pat, l); } public static boolean jmatchAny(String pat, Iterable l, Matches m) { return jmatch_any(pat, l, m); } public static boolean jmatchAny(List patterns, Iterable l) { return jmatch_any(patterns, l, null); } public static boolean jmatchAny(List patterns, Iterable l, Matches m) { return jmatch_any(patterns, l, m); } public static Object callAndMake_orF1(Object function, Object... args) { if (function instanceof F1) return callF(function, args); if (function == null) return null; return callAndMake_orDirect((String) function, args); } public static List getJMatches_all(String pat, Iterable l) { Matches m = new Matches(); List out = new ArrayList(); for (String s : unnull(l)) if (jmatch(pat, s, m)) { out.add(m); m = new Matches(); } return out; } public static Object callAndMake_orF2(Object function, Object... args) { if (function instanceof F2) return callF(function, args); if (function == null) return null; return callAndMake_orDirect((String) function, args); } public static List ai_applyWordSplitPattern1(List tokP, List tokI) { List indices = indicesOfSubList(tokP, ll("", "{}", "")); if (empty(indices)) return tokI; List tokI_original = tokI; tokI = cloneList(tokI); for (int i : indices) { String l = get(tokP, i - 1), r = get(tokP, i + 3); if (startsWith(l, "$") && isIdentifier(l) && isIdentifier(r)) { String x = get(tokI, i - 1); if (!ewic(x, r)) return tokI_original; tokI.set(i - 1, dropLast(x, l(r))); tokI.add(i, ""); tokI.add(i + 1, "{}"); tokI.add(i + 2, ""); tokI.add(i + 3, takeLast(x, l(r))); } } return tokI; } public static Map zipTwoListsToCIMap_strict_withoutEquals(List l1, List l2) { int n = l(l1); if (n != l(l2)) return null; Map map = ciMap(); for (int i = 0; i < n; i++) if (!strictPutICIfKeyNotEqualToValue(map, l1.get(i), l2.get(i))) return null; return map; } public static boolean gazelle_addMatch(RuleEngine2_MatchedRule mr, Map map, List tokC, List tokI, Object... __) { boolean debug = boolPar("debug", __); for (Object massager : unnull(mr.rule.mapMassagers)) { boolean wasNull = map == null; map = (Map) callF(massager, map, tokC, tokI, mr); if (debug && map == null && !wasNull) print("mapMassager returned null: " + massager); } if (map == null) return false; if (!addMapToMapWithoutOverwritingIC(mr.map, map)) { if (debug) print("Adding map failed"); return false; } mr.flush(); return true; } public static String strWithIdentityHashCode(Object o) { return o == null ? "null" : "[" + identityHashCode(o) + "] " + str(o); } public static String nullIfEmpty(String s) { return isEmpty(s) ? null : s; } public static Map nullIfEmpty(Map map) { return isEmpty(map) ? null : map; } public static List nullIfEmpty(List l) { return isEmpty(l) ? null : l; } public static Map, Integer> ai_ruleEngine2_mappingQualities(RuleEngine2.Rule rule) { Map, Integer> map = new HashMap(); Matches m = new Matches(); for (String s : rule.comments) if (match("changing * to * is *", s, m)) { int value = eqic(m.unq(0), "ok") ? 1 : eqic(m.unq(0), "bad") ? -1 : 0; map.put(pair(m.unq(1), m.unq(2)), value); } return map; } public static boolean isCurlyBraced(String s) { List tok = tok_combineCurlyBrackets_keep(javaTok(s)); return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}"); } public static int numberOfJavaTokens(String s) { return l(javaTokC(s)); } public static String curlyBrace(String s) { return "{" + s + "}"; } public static List sortByCalculatedFieldDesc_inPlace(List l, final Object f) { sort(l, new Comparator() { public int compare(A b, A a) { return stdcompare((Object) callF(f, a), (Object) callF(f, b)); } }); return l; } public static List sortByCalculatedFieldDesc_inPlace(Object f, List c) { return sortByCalculatedFieldDesc_inPlace(c, f); } public static String[] drop(int n, String[] a) { n = Math.min(n, a.length); String[] b = new String[a.length - n]; System.arraycopy(a, n, b, 0, b.length); return b; } public static Object[] drop(int n, Object[] a) { n = Math.min(n, a.length); Object[] b = new Object[a.length - n]; System.arraycopy(a, n, b, 0, b.length); return b; } public static ArrayList toList(A[] a) { return asList(a); } public static ArrayList toList(int[] a) { return asList(a); } public static ArrayList toList(Set s) { return asList(s); } public static ArrayList toList(Iterable s) { return asList(s); } public static Map safeUnstructureMap(String s) { return (Map) safeUnstructure(s); } public static boolean canPutAllStrictlyIC(Map map, Map map2) { { final Map __642 = unnull(map2); for (A key : keys(__642)) { String value = __642.get(key); if (!canPutStrictlyIC(map, key, value)) return false; } } return true; } public static Map mergeMaps(Map... maps) { Map map = null; for (Map m : maps) { if (map == null) map = similarEmptyMap(m); map.putAll(m); } return map; } public static String stringPar(Object[] params, String name) { return stringOptPar(params, name); } public static String stringPar(String name, Object[] params) { return stringOptPar(params, name); } public static String stringPar(String name, Object[] params, String defaultValue) { return optPar(name, params, defaultValue); } public static Object dm_call(Object moduleOrID, String method, Object... args) { Object mod = dm_getModule(moduleOrID); if (mod == null) return null; AutoCloseable __59 = dm_enter(mod); try { return call_withVarargs(mod, method, args); } finally { _close(__59); } } public static String gazelle_rumCRUD() { return dm_require("#1022322/RecentlyUsedMappings"); } public static List matchAll(String pat, Iterable l) { List l2 = new ArrayList(); Matches m = new Matches(); if (l != null) for (String s : l) if (match(pat, s, m)) { l2.add(m); m = new Matches(); } return l2; } public static > A printLinesWithIndent(String indent, A lines) { if (lines != null) for (B s : lines) printIndent(indent, s); return lines; } public static String defaultIndent() { return indent(indent_default); } public 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); } public 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; } public static List repeat(int n, A a) { return repeat(a, n); } public static int indent_default = 2; public static String indent(int indent) { return repeat(' ', indent); } public static String indent(int indent, String s) { return indent(repeat(' ', indent), s); } public static String indent(String indent, String s) { return indent + s.replace("\n", "\n" + indent); } public static String indent(String s) { return indent(indent_default, s); } public static List indent(String indent, List lines) { List l = new ArrayList(); for (String s : lines) l.add(indent + s); return l; } public static Map myFrames_list = weakHashMap(); public static List myFrames() { return swing(new F0>() { public List get() { try { return keysList(myFrames_list); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret keysList(myFrames_list);"; } }); } public static List splitAtTokens(String s, List tokens) { return splitAtTokens(javaTok(s), tokens); } public static List splitAtTokens(List tok, List tokens) { List l = new ArrayList(); int i = 0; while (i < l(tok)) { int j = indexOfSubList(tok, tokens, i); if (i >= l(tok)) break; if (j < 0) j = l(tok); l.add(trimJoin(tok.subList(i, j))); i = j + l(tokens); } return l; } public static List splitAtTokens(List tok, String... tokens) { List l = new ArrayList(); int i = 0; while (i < l(tok)) { int j = indexOfSubList(tok, tokens, i); if (i >= l(tok)) break; if (j < 0) j = l(tok); l.add(trimJoin(tok.subList(i, j))); i = j + l(tokens); } return l; } public static int findEndOfBracketPart(List cnc, int i) { int j = i + 2, level = 1; while (j < cnc.size()) { if (eqOneOf(cnc.get(j), "{", "(")) ++level; else if (eqOneOf(cnc.get(j), "}", ")")) --level; if (level == 0) return j + 1; ++j; } return cnc.size(); } public static String joinSubList(List l, int i, int j) { return join(subList(l, i, j)); } public static String joinSubList(List l, int i) { return join(subList(l, i)); } public static List replaceSubList(List l, List x, List y) { return replaceSublist(l, x, y); } public static List replaceSubList(List l, int fromIndex, int toIndex, List y) { return replaceSublist(l, fromIndex, toIndex, y); } public static String javaTok_substringN(String s, int i, int j) { if (i == j) return ""; if (j == i + 1 && s.charAt(i) == ' ') return " "; return s.substring(i, j); } public static void arraycopy(Object[] a, Object[] b) { int n = min(a.length, b.length); for (int i = 0; i < n; i++) b[i] = a[i]; } public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) { System.arraycopy(src, srcPos, dest, destPos, n); } public static List takeLast(List l, int n) { return newSubList(l, l(l) - n); } public static List takeLast(int n, List l) { return takeLast(l, n); } public static String takeLast(int n, String s) { return substring(s, l(s) - n); } public static String takeLast(String s, int n) { return substring(s, l(s) - n); } public static Object dm_getModule(Object moduleOrID) { if (moduleOrID == null || eq(moduleOrID, "")) return null; if (isString(moduleOrID) && isIdentifier(((String) moduleOrID))) return dm_getService(((String) moduleOrID)); if (isStringOrIntOrLong(moduleOrID)) return dm_callOS("getDynModuleByID", str(moduleOrID)); return dm_resolveModule(moduleOrID); } public static AutoCloseable dm_enter(Object mod) { return (AutoCloseable) callOpt(dm_getModule(mod), "enter"); } public static String dm_makeModule(String moduleLibID) { return (String) dm_callOS("makeModule", moduleLibID); } public static Map syncMRUCache(int size) { return synchroMap(new MRUCache(size)); } public static boolean regexpFinds(String pat, String s) { return regexp(pat, s).find(); } public static boolean regexpFinds(Pattern pat, String s) { return regexp(pat, s).find(); } public static boolean hasMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args) != null; } public static ThreadLocal makeAndCall_initChild = new ThreadLocal(); public static Object makeAndCall_cached(String functionName, Object... args) { Class c = loadFunctions_cached(functionName); AutoCloseable closer = (AutoCloseable) (callF(makeAndCall_initChild.get(), c)); AutoCloseable __852 = closer; try { return preciseCall(c, functionName, args); } finally { _close(__852); } } public static List javaTokPlusPeriod(String s) { List tok = new ArrayList(); int l = s.length(); int i = 0; while (i < l) { int j = i; char c; String cc; while (j < l) { c = s.charAt(j); cc = s.substring(j, Math.min(j + 2, l)); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (cc.equals("/*")) { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (cc.equals("//")) { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); cc = s.substring(i, Math.min(i + 2, l)); if (c == (char) 0x201C || c == (char) 0x201D) c = '"'; if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { char _c = s.charAt(j); if (_c == (char) 0x201C || _c == (char) 0x201D) _c = '"'; if (_c == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } if (j - 1 >= i + 1) { tok.add(opener + s.substring(i + 1, j - 1) + opener); i = j; continue; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); else if (Character.isDigit(c)) do ++j; while (j < l && Character.isDigit(s.charAt(j))); else if (cc.equals("[[")) { do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]")); j = Math.min(j + 2, l); } else if (cc.equals("[=") && 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 if (s.substring(j, Math.min(j + 3, l)).equals("...")) j += 3; else if (c == '$' || c == '#') do ++j; while (j < l && Character.isDigit(s.charAt(j))); else ++j; tok.add(s.substring(i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } public static boolean isNonNegativeInteger(String s) { int n = l(s); if (n == 0) return false; int i = 0; while (i < n) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } public static betterCIComparator_C betterCIComparator_instance; public static betterCIComparator_C betterCIComparator() { if (betterCIComparator_instance == null) betterCIComparator_instance = new betterCIComparator_C(); return betterCIComparator_instance; } public static class betterCIComparator_C implements Comparator { public int compare(String s1, String s2) { if (s1 == null) return s2 == null ? 0 : -1; if (s2 == null) return 1; int n1 = s1.length(); int n2 = s2.length(); int min = Math.min(n1, n2); for (int i = 0; i < min; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 != c2) { c1 = Character.toUpperCase(c1); c2 = Character.toUpperCase(c2); if (c1 != c2) { c1 = Character.toLowerCase(c1); c2 = Character.toLowerCase(c2); if (c1 != c2) { return c1 - c2; } } } } return n1 - n2; } } public static int charDiff(char a, char b) { return (int) a - (int) b; } public static int charDiff(String a, char b) { return charDiff(stringToChar(a), b); } public static void setOpt_raw(Object o, String field, Object value) { try { if (o == null) return; if (o instanceof Class) setOpt_raw((Class) o, field, value); else { Field f = setOpt_raw_findField(o.getClass(), field); if (f != null) { f.setAccessible(true); smartSet(f, o, value); } } } catch (Exception __e) { throw rethrow(__e); } } public static void setOpt_raw(Class c, String field, Object value) { try { if (c == null) return; Field f = setOpt_raw_findStaticField(c, field); if (f != null) { f.setAccessible(true); smartSet(f, null, value); } } catch (Exception __e) { throw rethrow(__e); } } public static Field setOpt_raw_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; } public static Field setOpt_raw_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; } public static Method findMethodNamed(Object obj, String method) { if (obj == null) return null; if (obj instanceof Class) return findMethodNamed((Class) obj, method); return findMethodNamed(obj.getClass(), method); } public static Method findMethodNamed(Class c, String method) { while (c != null) { for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) { m.setAccessible(true); return m; } c = c.getSuperclass(); } return null; } public static void upgradeJavaXAndRestart() { run("#1001639"); restart(); sleep(); } public static List javaTokWithExisting(String s, List existing) { ++javaTok_n; int nExisting = javaTok_opt && existing != null ? existing.size() : 0; ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList(); int l = s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c, d; 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; } if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else 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); 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) { if (s.charAt(j) == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } 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; if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } public static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) { return t.length() == j - i && s.regionMatches(i, t, 0, j - i); } public static Class getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } public static Class getClass(Object o) { return o instanceof Class ? (Class) o : o.getClass(); } public 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); } } public static String classNameToVM(String name) { return name.replace(".", "$"); } public static List> _threadInheritInfo_retrievers = synchroList(); public static void _threadInheritInfo(Object info) { if (info == null) return; pcallFAll(_threadInheritInfo_retrievers, (Map) info); } public static Object vm_generalMap_put(Object key, Object value) { return mapPutOrRemove(vm_generalMap(), key, value); } public static Map newWeakMap() { return newWeakHashMap(); } public static WeakReference newWeakReference(A a) { return a == null ? null : new WeakReference(a); } public static Object callFunction(Object f, Object... args) { return callF(f, args); } public static volatile Object isAllowed_function; public static volatile boolean isAllowed_all = true; public static boolean isAllowed(String askingMethod, Object... args) { Object f = vm_generalMap_get("isAllowed_function"); if (f != null && !isTrue(callF(f, askingMethod, args))) return false; return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args)); } public static long round(double d) { return Math.round(d); } public static File getProgramFile(String progID, String fileName) { if (new File(fileName).isAbsolute()) return new File(fileName); return new File(getProgramDir(progID), fileName); } public static File getProgramFile(String fileName) { return getProgramFile(getProgramID(), fileName); } public static String hmsWithColons() { return hmsWithColons(now()); } public static String hmsWithColons(long time) { return new SimpleDateFormat("HH:mm:ss").format(time); } public static String getComputerID_quick() { return computerID(); } public static int gzInputStream_defaultBufferSize = 65536; public static GZIPInputStream gzInputStream(File f) { try { return gzInputStream(new FileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } public static GZIPInputStream gzInputStream(File f, int bufferSize) { try { return gzInputStream(new FileInputStream(f), bufferSize); } catch (Exception __e) { throw rethrow(__e); } } public static GZIPInputStream gzInputStream(InputStream in) { return gzInputStream(in, gzInputStream_defaultBufferSize); } public static GZIPInputStream gzInputStream(InputStream in, int bufferSize) { try { return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in); } catch (Exception __e) { throw rethrow(__e); } } public static String _userHome; public static String userHome() { if (_userHome == null) { if (isAndroid()) _userHome = "/storage/sdcard0/"; else _userHome = System.getProperty("user.home"); } return _userHome; } public static File userHome(String path) { return new File(userDir(), path); } public static File standardLogFile() { return getProgramFile("log"); } public static void logQuoted(String logFile, String line) { logQuoted(getProgramFile(logFile), line); } public static void logQuoted(File logFile, String line) { appendToFile(logFile, quote(line) + "\n"); } public static long now_virtualTime; public static long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } public static A _recordNewSwingComponent(A c) { if (c != null) callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c); return c; } public static JLabel jlabel(final String text) { return swingConstruct(BetterLabel.class, text); } public static JLabel jlabel() { return jlabel(" "); } public static void enableWordWrapForTextArea(final JTextArea ta) { if (ta != null) { swing(new Runnable() { public void run() { try { ta.setLineWrap(true); ta.setWrapStyleWord(true); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ta.setLineWrap(true);\r\n ta.setWrapStyleWord(true);"; } }); } } public static JTextArea jtextarea() { return jTextArea(); } public static JTextArea jtextarea(String text) { return jTextArea(text); } public static boolean setText_opt = true; public static A setText(A c, Object text) { setText((Object) c, text); return c; } public static A setText(final A c, Object text) { final String s = strUnnull(text); { swing(new Runnable() { public void run() { try { c.getEditor().setItem(s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.getEditor().setItem(s);"; } }); } return c; } public static void setText(JLabel c, Object text) { setText((Object) c, text); } public static JButton setText(JButton c, Object text) { setText((Object) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text))); return c; } public static A setText(final A c, Object text) { if (c == null) return null; final String s = strUnnull(text); { swing(new Runnable() { public void run() { try { if (!setText_opt || neq(callOpt(c, "getText"), s)) call(c, "setText", s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n call(c, \"setText\", s);"; } }); } return c; } public static JTextField onEnter(final JTextField tf, final Object action) { if (action == null || tf == null) return tf; tf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { tf.selectAll(); callF(action); } catch (Throwable __e) { messageBox(__e); } } }); return tf; } public static JButton onEnter(JButton btn, final Object action) { if (action == null || btn == null) return btn; btn.addActionListener(actionListener(action)); return btn; } public static JList onEnter(JList list, Object action) { list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action))); return list; } public static JComboBox onEnter(final JComboBox cb, final Object action) { { swing(new Runnable() { public void run() { try { if (cb.isEditable()) { JTextField text = (JTextField) cb.getEditor().getEditorComponent(); onEnter(text, action); } else { cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter"); cb.getActionMap().put("enter", abstractAction("", new Runnable() { public void run() { try { cb.hidePopup(); callF(action); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.hidePopup(); callF(action);"; } })); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (cb.isEditable()) {\r\n JTextField text = (JTextField) cb.getEditor().g..."; } }); } return cb; } public static JTable onEnter(final JTable table, final Object action) { table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter"); table.getActionMap().put("Enter", new AbstractAction() { public void actionPerformed(ActionEvent e) { callF(action, table.getSelectedRow()); } }); return table; } public static JTextField onEnter(Object action, JTextField tf) { return onEnter(tf, action); } public static A heldInstance(Class c) { List l = holdInstance_l.get(); for (int i = l(l) - 1; i >= 0; i--) { Object o = l.get(i); if (isInstanceOf(o, c)) return (A) o; } throw fail("No instance of " + className(c) + " held"); } public static ActionListener actionListener(final Object runnable) { return actionListener(runnable, null); } public static ActionListener actionListener(final Object runnable, final Object instanceToHold) { if (runnable instanceof ActionListener) return (ActionListener) runnable; final Object info = _threadInfo(); return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { _threadInheritInfo(info); AutoCloseable __410 = holdInstance(instanceToHold); try { callF(runnable); } finally { _close(__410); } } catch (Throwable __e) { messageBox(__e); } } }; } public static int toInt_checked(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } public static boolean isLocalSnippetID(String snippetID) { return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID)); } public static boolean isLocalSnippetID(long snippetID) { return snippetID >= 1000 && snippetID <= 9999; } public static String localSnippetTitle(String snippetID) { if (!isLocalSnippetID(snippetID)) return null; File f = localSnippetFile(snippetID); if (!f.exists()) return null; return or2(getFileInfoField(dropExtension(f), "Title"), "Unnamed"); } public static boolean isImageServerSnippet(long id) { return id >= 1100000 && id < 1200000; } public static String imageServerURL() { return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/"); } public static String muricaCredentialsQuery() { return htmlQuery(muricaCredentials()); } public static boolean isGeneralFileServerSnippet(long id) { return id >= 1400000 && id < 1500000; } public static String standardCredentials_noCookies() { return standardCredentials() + "&noCookies=1"; } public static boolean saveTextFileIfChanged(File f, String contents) { return saveTextFileIfDifferent(f, contents); } public static File snippetTitle_cacheFile(String snippetID) { return javaxCachesDir("Snippet Titles/" + psI(snippetID)); } public static String fsI(String id) { return formatSnippetID(id); } public static String fsI(long id) { return formatSnippetID(id); } public static int imageIcon_cacheSize = 10; public static boolean imageIcon_verbose; public static Map imageIcon_cache; public static Lock imageIcon_lock = lock(); public static ThreadLocal imageIcon_fixGIF = new ThreadLocal(); public static ImageIcon imageIcon(String imageID) { try { if (imageID == null) return null; Lock __1864 = imageIcon_lock; lock(__1864); try { if (imageIcon_cache == null) imageIcon_cache = new MRUCache(imageIcon_cacheSize); imageID = fsI(imageID); ImageIcon ii = imageIcon_cache.get(imageID); if (ii == null) { if (imageIcon_verbose) print("Loading image icon: " + imageID); File f = loadBinarySnippet(imageID); Boolean b = imageIcon_fixGIF.get(); if (!isFalse(b)) ii = new ImageIcon(loadBufferedImageFixingGIFs(f)); else ii = new ImageIcon(f.toURI().toURL()); } else imageIcon_cache.remove(imageID); imageIcon_cache.put(imageID, ii); return ii; } finally { unlock(__1864); } } catch (Exception __e) { throw rethrow(__e); } } public static ImageIcon imageIcon(File f) { try { return new ImageIcon(f.toURI().toURL()); } catch (Exception __e) { throw rethrow(__e); } } public static ImageIcon imageIcon(Image img) { return new ImageIcon(img); } public static Map vm_generalMap_map; public static Map vm_generalMap() { if (vm_generalMap_map == null) vm_generalMap_map = (Map) get(javax(), "generalMap"); return vm_generalMap_map; } public static String htmlencode_forParams(String s) { if (s == null) return ""; StringBuilder out = new StringBuilder(Math.max(16, s.length())); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c > 127 || c == '"' || c == '<' || c == '>') { out.append("&#"); out.append((int) c); out.append(';'); } else out.append(c); } return out.toString(); } public static void pcallFAll(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) pcallF(f, args); } public static void pcallFAll(Iterator it, Object... args) { while (it.hasNext()) pcallF(it.next(), args); } public static boolean endsWithIgnoreCase(String a, String b) { int la = l(a), lb = l(b); return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb); } public static boolean endsWithIgnoreCase(String a, String b, Matches m) { if (!endsWithIgnoreCase(a, b)) return false; m.m = new String[] { substring(a, 0, l(a) - l(b)) }; return true; } public static BufferedReader bufferedReader(Reader r) { return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r); } public static CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) { class IFF2 extends CloseableIterableIterator { public A a; public boolean done; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } public void getNext() { if (done || a != null) return; a = f.get(); done = a == null; } public void close() throws Exception { if (closeable != null) closeable.close(); } } ; return new IFF2(); } public static String readLineFromReaderWithClose(BufferedReader r) { try { String s = r.readLine(); if (s == null) r.close(); return s; } catch (Exception __e) { throw rethrow(__e); } } public static AutoCloseable _wrapIOCloseable(final AutoCloseable c) { return c == null ? null : new AutoCloseable() { public String toString() { return "c.close();\r\n _registerIO(c, null, false);"; } public void close() throws Exception { c.close(); _registerIO(c, null, false); } }; } public static A _registerIOWrap(A wrapper, Object wrapped) { return wrapper; } public static FileInputStream newFileInputStream(File path) throws IOException { return newFileInputStream(path.getPath()); } public static FileInputStream newFileInputStream(String path) throws IOException { FileInputStream f = new FileInputStream(path); _registerIO(f, path, true); return f; } public static int indexOfIgnoreCase_manual(String a, String b) { int la = l(a), lb = l(b); if (la < lb) return -1; int n = la - lb; loop: for (int i = 0; i <= n; i++) { for (int j = 0; j < lb; j++) { char c1 = a.charAt(i + j), c2 = b.charAt(j); if (!eqic(c1, c2)) continue loop; } return i; } return -1; } public static List dropPunctuation_keep = litlist("*", "<", ">"); public static List dropPunctuation(List tok) { tok = new ArrayList(tok); for (int i = 1; i < tok.size(); i += 2) { String t = tok.get(i); if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) { tok.set(i - 1, tok.get(i - 1) + tok.get(i + 1)); tok.remove(i); tok.remove(i); i -= 2; } } return tok; } public static String dropPunctuation(String s) { return join(dropPunctuation(nlTok(s))); } public static String shortenClassName(String name) { if (name == null) return null; int i = lastIndexOf(name, "$"); if (i < 0) i = lastIndexOf(name, "."); return i < 0 ? name : substring(name, i + 1); } public static Map javaTokForJFind_array_cache = synchronizedMRUCache(1000); public static String[] javaTokForJFind_array(String s) { String[] tok = javaTokForJFind_array_cache.get(s); if (tok == null) javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s)))); return tok; } public static int findCodeTokens(List tok, String... tokens) { return findCodeTokens(tok, 1, false, tokens); } public static int findCodeTokens(List tok, boolean ignoreCase, String... tokens) { return findCodeTokens(tok, 1, ignoreCase, tokens); } public static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String... tokens) { return findCodeTokens(tok, startIdx, ignoreCase, tokens, null); } public static HashSet findCodeTokens_specials = lithashset("*", "", "", "", "\\*"); public static boolean findCodeTokens_debug; public static int findCodeTokens_indexed, findCodeTokens_unindexed; public static int findCodeTokens_bails, findCodeTokens_nonbails; public static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) { if (findCodeTokens_debug) { if (eq(getClassName(tok), "main$IndexedList2")) findCodeTokens_indexed++; else findCodeTokens_unindexed++; } int end = tok.size() - tokens.length * 2 + 2, nTokens = tokens.length; int i = startIdx | 1; String firstToken = tokens[0]; if (!ignoreCase && !findCodeTokens_specials.contains(firstToken)) { while (i < end && !firstToken.equals(tok.get(i))) i += 2; } outer: for (; i < end; i += 2) { for (int j = 0; j < nTokens; j++) { String p = tokens[j], t = tok.get(i + j * 2); boolean match; if (eq(p, "*")) match = true; else if (eq(p, "")) match = isQuoted(t); else if (eq(p, "")) match = isIdentifier(t); else if (eq(p, "")) match = isInteger(t); else if (eq(p, "\\*")) match = eq("*", t); else match = ignoreCase ? eqic(p, t) : eq(p, t); if (!match) continue outer; } if (condition == null || checkTokCondition(condition, tok, i - 1)) return i; } return -1; } public static String jreplaceExpandRefs(String s, List tokref) { List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { if (tok.get(i).startsWith("$") && isInteger(tok.get(i).substring(1))) { String x = tokref.get(-1 + parseInt(tok.get(i).substring(1)) * 2); tok.set(i, x); } } return join(tok); } public static void clearAllTokens(List tok) { for (int i = 0; i < tok.size(); i++) tok.set(i, ""); } public static void clearAllTokens(List tok, int i, int j) { for (; i < j; i++) tok.set(i, ""); } public static List reTok(List tok) { replaceCollection(tok, javaTok(tok)); return tok; } public static List reTok(List tok, int i) { return reTok(tok, i, i + 1); } public static List reTok(List tok, int i, int j) { i = i & ~1; j = j | 1; List t = javaTok(join(subList(tok, i, j))); replaceListPart(tok, i, j, t); return tok; } public static Map objectToMap(Object o) { try { if (o instanceof Map) return (Map) o; TreeMap map = new TreeMap(); Class c = o.getClass(); while (c != Object.class) { Field[] fields = c.getDeclaredFields(); for (final Field field : fields) { if ((field.getModifiers() & Modifier.STATIC) != 0) continue; field.setAccessible(true); final Object value = field.get(o); if (value != null) map.put(field.getName(), value); } c = c.getSuperclass(); } if (o instanceof DynamicObject) map.putAll(((DynamicObject) o).fieldValues); return map; } catch (Exception __e) { throw rethrow(__e); } } public static List> objectToMap(Iterable l) { if (l == null) return null; List x = new ArrayList(); for (Object o : l) x.add(objectToMap(o)); return x; } public static String[] asStringArray(Collection c) { return toStringArray(c); } public static String[] asStringArray(Object o) { return toStringArray(o); } public static boolean isLetter(char c) { return Character.isLetter(c); } public static List mechList_opt(String name) { return mechList_opt_tlft(name); } public static List tok_splitAtComma(String s) { return tok_splitAtComma(javaTok(s)); } public static List tok_splitAtComma(List tok) { List out = new ArrayList(); for (int i = 0; i < l(tok); i++) { int j = smartIndexOf(tok, ",", i); out.add(joinSubList(tok, i + 1, j - 1)); i = j; } return out; } public static String optionalCurlyBrace(String s) { return isCurlyBraced(s) ? s : curlyBrace(s); } public static String tok_unCurlyBracket(String s) { return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s; } public static boolean jmatch_any(String pat, Iterable l) { return jmatch_any(pat, l, null); } public static boolean jmatch_any(String pat, Iterable l, Matches m) { for (String s : unnull(l)) if (jmatch(pat, s, m)) return true; return false; } public static boolean jmatch_any(List patterns, Iterable l, Matches m) { if (nempty(patterns)) for (String s : unnull(l)) for (String pat : patterns) if (jmatch(pat, s, m)) return true; return false; } public static List indicesOfSubList(List x, List y) { List l = new ArrayList(); int i = 0; while (true) { int j = indexOfSubList(x, y, i); if (j < 0) break; l.add(j); i = j + 1; } return l; } public static boolean strictPutICIfKeyNotEqualToValue(Map map, String key, String value) { if (eqic(key, value)) return true; return strictPutIC(map, key, value); } public static boolean addMapToMapWithoutOverwritingIC(Map map, Map adding) { if (!canPutAllStrictlyIC(map, adding)) return false; { final Map __776 = unnull(adding); for (A key : keys(__776)) { String value = __776.get(key); strictPutIC(map, key, value); } } return true; } public static int identityHashCode(Object o) { return System.identityHashCode(o); } public static boolean isEmpty(Collection c) { return c == null || c.isEmpty(); } public static boolean isEmpty(CharSequence s) { return s == null || s.length() == 0; } public static boolean isEmpty(Object[] a) { return a == null || a.length == 0; } public static boolean isEmpty(byte[] a) { return a == null || a.length == 0; } public static boolean isEmpty(Map map) { return map == null || map.isEmpty(); } public static List tok_combineCurlyBrackets_keep(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && eq(t, "{")) { int j = findEndOfCurlyBracketPart(tok, i); l.add(joinSubList(tok, i, j)); i = j - 1; } else l.add(t); } return l; } public static boolean startsWithAndEndsWith(String s, String prefix, String suffix) { return startsWith(s, prefix) && endsWith(s, suffix); } public static void sort(T[] a, Comparator c) { Arrays.sort(a, c); } public static void sort(T[] a) { Arrays.sort(a); } public static void sort(List a, Comparator c) { Collections.sort(a, c); } public static void sort(List a) { Collections.sort(a); } public static boolean canPutStrictlyIC(Map map, A key, String value) { if (!(map != null && key != null && value != null)) return true; String old = map.get(key); return old == null || eqic(old, value); } public static String stringOptPar(Object[] params, String name) { return (String) optPar(params, name); } public 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); 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); 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"); } } catch (Exception __e) { throw rethrow(__e); } } public static String dm_require(String moduleLibID) { return dm_makeModule(moduleLibID); } public static ThreadLocal> holdInstance_l = new ThreadLocal(); public static AutoCloseable holdInstance(Object o) { if (o == null) return null; listThreadLocalAdd(holdInstance_l, o); return new AutoCloseable() { public void close() { listThreadLocalPopLast(holdInstance_l); } }; } public static Map weakHashMap() { return newWeakHashMap(); } public static List replaceSublist(List l, List x, List y) { if (x == null) return l; int i = 0; while (true) { i = indexOfSubList(l, x, i); if (i < 0) break; removeSubList(l, i, i + l(x)); l.addAll(i, y); i += l(y); } return l; } public static List replaceSublist(List l, int fromIndex, int toIndex, List y) { removeSubList(l, fromIndex, toIndex); l.addAll(fromIndex, y); return l; } public static List newSubList(List l, int startIndex, int endIndex) { return cloneList(subList(l, startIndex, endIndex)); } public static List newSubList(List l, int startIndex) { return cloneList(subList(l, startIndex)); } public static boolean isString(Object o) { return o instanceof String; } public static Object dm_getService(String serviceName) { return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName))); } public static boolean isStringOrIntOrLong(Object o) { return o instanceof String || o instanceof Integer || o instanceof Long; } public static Object dm_callOS(String functionName, Object... args) { return call(dm_os(), functionName, args); } public static Object dm_resolveModule(Object moduleOrStem) { return dm_callOS("resolveModule", moduleOrStem); } public static Matcher regexp(String pat, String s) { return regexp(compileRegexp(pat), s); } public static Matcher regexp(Pattern pat, String s) { return pat.matcher(unnull(s)); } public 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); } } public static HashMap, Class> loadFunctions_cache = new HashMap(); public static Lock loadFunctions_cached_lock = lock(); public static boolean loadFunctions_preferDiskCache; public static Class loadFunctions_cached(String... functions) { return loadFunctions_cached(asList(functions)); } public static Class loadFunctions_cached(Collection functions) { TreeSet functionSet = new TreeSet(functions); Lock __939 = loadFunctions_cached_lock; lock(__939); try { Class c = loadFunctions_cache.get(functionSet); if (c != null) return c; String cached = getTranspiledStandardFunctionsIfCached(functionSet); String transpilation = null; if (cached != null && (loadFunctions_preferDiskCache || standardFunctionsCacheUpToDate(functionSet))) transpilation = cached; if (transpilation != null) { print("Loading " + joinWithPlus(functionSet)); c = veryQuickJava_finish(transpilation, emptyList()); } if (c == null) c = loadFunctions(functionSet); loadFunctions_cache.put(functionSet, c); assertNotNull(loadFunctions_cache.get(functionSet)); return c; } finally { unlock(__939); } } public static boolean preciseCall_debug; public static Object preciseCall(Object o, String method, Object... args) { try { if (o instanceof Class) { _MethodCache cache = callOpt_getCache(((Class) o)); List methods = cache.cache.get(method); Lowest best = new Lowest(); if (methods != null) for (Method m : methods) { { if (!(isStaticMethod(m))) continue; } int score = methodApplicabilityScore(m, args); if (score < Integer.MAX_VALUE) { if (preciseCall_debug) print("Method score: " + m + " " + score); best.put(m, score); } } Method m = best.get(); if (m != null) return invokeMethod(m, null, args); return call_withVarargs(((Class) o), method, args); } else throw todo(); } catch (Exception __e) { throw rethrow(__e); } } public static char stringToChar(String s) { if (l(s) != 1) throw fail("bad stringToChar: " + s); return firstChar(s); } public static Class run(String progID, String... args) { Class main = hotwire(progID); callMain(main, args); return main; } public static void restart() { Object j = getJavaX(); call(j, "cleanRestart", get(j, "fullArgs")); } public 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; } public static File getProgramDir() { return programDir(); } public static File getProgramDir(String snippetID) { return programDir(snippetID); } public static String _computerID; public static Lock computerID_lock = lock(); public static String computerID() { if (_computerID == null) { Lock __517 = computerID_lock; lock(__517); try { if (_computerID != null) return _computerID; File file = computerIDFile(); _computerID = loadTextFile(file.getPath()); if (_computerID == null) { _computerID = loadTextFile(userDir(".tinybrain/computer-id")); if (_computerID == null) _computerID = makeRandomID(12, new SecureRandom()); saveTextFile(file, _computerID); } } finally { unlock(__517); } } return _computerID; } public static File userDir() { return new File(userHome()); } public static File userDir(String path) { return new File(userHome(), path); } public static Lock appendToFile_lock = lock(); public static boolean appendToFile_keepOpen; public static HashMap appendToFile_writers = new HashMap(); public static void appendToFile(String path, String s) { try { Lock __336 = appendToFile_lock; lock(__336); try { mkdirsForFile(new File(path)); path = getCanonicalPath(path); Writer writer = appendToFile_writers.get(path); if (writer == null) { writer = new BufferedWriter(new OutputStreamWriter(newFileOutputStream(path, true), "UTF-8")); if (appendToFile_keepOpen) appendToFile_writers.put(path, writer); } writer.write(s); if (!appendToFile_keepOpen) writer.close(); } finally { unlock(__336); } } catch (Exception __e) { throw rethrow(__e); } } public static void appendToFile(File path, String s) { if (path != null) appendToFile(path.getPath(), s); } public static void cleanMeUp_appendToFile() { AutoCloseable __338 = tempCleaningUp(); try { Lock __337 = appendToFile_lock; lock(__337); try { closeAllWriters(values(appendToFile_writers)); appendToFile_writers.clear(); } finally { unlock(__337); } } finally { _close(__338); } } public static A swingConstruct(final Class c, final Object... args) { return swing(new F0() { public A get() { try { return nuObject(c, args); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret nuObject(c, args);"; } }); } public static JTextArea jTextArea() { return jTextArea(""); } public static JTextArea jTextArea(final String text) { return jTextAreaWithUndo(text); } public static String strUnnull(Object o) { return o == null ? "" : str(o); } public static String jlabel_textAsHTML_center_ifNeeded(String text) { if (swic(text, "") && ewic(text, "")) return text; if (!containsNewLines(text)) return text; return jlabel_textAsHTML_center(text); } public static void messageBox(final String msg) { if (headless()) print(msg); else { swing(new Runnable() { public void run() { try { JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES..."; } }); } } public static void messageBox(Throwable e) { printStackTrace(e); messageBox(hideCredentials(innerException2(e))); } public static KeyListener enterKeyListener(final Object action) { return new KeyAdapter() { public void keyPressed(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_ENTER) pcallF(action); } }; } public static Runnable rCallOnSelectedListItem(final JList list, final Object action) { return new Runnable() { public void run() { try { pcallF(action, getSelectedItem(list)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, getSelectedItem(list))"; } }; } public static AbstractAction abstractAction(String name, final Object runnable) { return new AbstractAction(name) { public void actionPerformed(ActionEvent evt) { pcallF(runnable); } }; } public static boolean isInstanceOf(Object o, Class type) { return type.isInstance(o); } public static File localSnippetFile(long snippetID) { return localSnippetsDir(snippetID + ".text"); } public static File localSnippetFile(String snippetID) { return localSnippetFile(parseSnippetID(snippetID)); } public static String getFileInfoField(File f, String field) { return getOneLineFileInfoField(f, field); } public static File dropExtension(File f) { return f == null ? null : fileInSameDir(f, dropExtension(f.getName())); } public static String dropExtension(String s) { return takeFirst(s, smartLastIndexOf(s, '.')); } public static String htmlQuery(Map params) { return params.isEmpty() ? "" : "?" + makePostData(params); } public static String htmlQuery(Object... data) { return htmlQuery(litmap(data)); } public static Object[] muricaCredentials() { String pass = muricaPassword(); return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0]; } public static String standardCredentials() { String user = standardCredentialsUser(); String pass = standardCredentialsPass(); if (nempty(user) && nempty(pass)) return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass); return ""; } public static boolean saveTextFileIfDifferent(File f, String contents) { if (eq(loadTextFile(f), contents)) return false; { saveTextFile(f, contents); return true; } } public static File javaxCachesDir_dir; public static File javaxCachesDir() { return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches"); } public static File javaxCachesDir(String sub) { return newFile(javaxCachesDir(), sub); } public static File loadBinarySnippet(String snippetID) { try { long id = parseSnippetID(snippetID); File f = DiskSnippetCache_getLibrary(id); if (fileSize(f) == 0) f = loadDataSnippetToFile(snippetID); return f; } catch (Exception __e) { throw rethrow(__e); } } public static boolean loadBufferedImageFixingGIFs_debug; public static ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal(); public static Image loadBufferedImageFixingGIFs(File file) { try { if (!file.exists()) return null; if (!isGIF(file)) return ImageIO.read(file); if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": checking gif"); ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next(); reader.setInput(ImageIO.createImageInputStream(file)); int numImages = reader.getNumImages(true); IIOMetadata imageMetaData = reader.getImageMetadata(0); String metaFormatName = imageMetaData.getNativeMetadataFormatName(); boolean foundBug = false; for (int i = 0; i < numImages && !foundBug; i++) { IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName); int nNodes = root.getLength(); for (int j = 0; j < nNodes; j++) { org.w3c.dom.Node node = root.item(j); if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) { String delay = ((IIOMetadataNode) node).getAttribute("delayTime"); if (Integer.parseInt(delay) == 0) { foundBug = true; } break; } } } if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug); Image image; if (!foundBug) { image = Toolkit.getDefaultToolkit().createImage(f2s(file)); } else { ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); { ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream); try { ImageWriter writer = ImageIO.getImageWriter(reader); writer.setOutput(ios); writer.prepareWriteSequence(null); for (int i = 0; i < numImages; i++) { BufferedImage frameIn = reader.read(i); IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName); int nNodes = root.getLength(); for (int j = 0; j < nNodes; j++) { org.w3c.dom.Node node = root.item(j); if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) { String delay = ((IIOMetadataNode) node).getAttribute("delayTime"); if (Integer.parseInt(delay) == 0) { ((IIOMetadataNode) node).setAttribute("delayTime", "10"); } break; } } IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null); metadata.setFromTree(metadata.getNativeMetadataFormatName(), root); IIOImage frameOut = new IIOImage(frameIn, null, metadata); writer.writeToSequence(frameOut, writer.getDefaultWriteParam()); } writer.endWriteSequence(); } finally { _close(ios); } } byte[] data = baoStream.toByteArray(); setVar(loadBufferedImageFixingGIFs_output.get(), data); if (loadBufferedImageFixingGIFs_debug) print("Data size: " + l(data)); image = Toolkit.getDefaultToolkit().createImage(data); } return image; } catch (Exception __e) { throw rethrow(__e); } } public static void _registerIO(Object object, String path, boolean opened) { } public static ArrayList litlist(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; } public static List nlTok(String s) { return javaTokPlusPeriod(s); } public static int lastIndexOf(String a, String b) { return a == null || b == null ? -1 : a.lastIndexOf(b); } public static int lastIndexOf(String a, char b) { return a == null ? -1 : a.lastIndexOf(b); } public static String[] codeTokensAsStringArray(List tok) { int n = max(0, (l(tok) - 1) / 2); String[] out = new String[n]; for (int i = 0; i < n; i++) out[i] = tok.get(i * 2 + 1); return out; } public static int jfind(String s, String in) { return jfind(javaTok(s), in); } public static int jfind(List tok, String in) { return jfind(tok, 1, in); } public static int jfind(List tok, int startIdx, String in) { return jfind(tok, startIdx, in, null); } public static int jfind(List tok, String in, Object condition) { return jfind(tok, 1, in, condition); } public static int jfind(List tok, int startIdx, String in, Object condition) { return jfind(tok, startIdx, javaTokForJFind_array(in), condition); } public static int jfind(List tok, List tokin) { return jfind(tok, 1, tokin); } public static int jfind(List tok, int startIdx, List tokin) { return jfind(tok, startIdx, tokin, null); } public static int jfind(List tok, int startIdx, String[] tokinC, Object condition) { return findCodeTokens(tok, startIdx, false, tokinC, condition); } public static int jfind(List tok, int startIdx, List tokin, Object condition) { return findCodeTokens(tok, startIdx, false, codeTokensAsStringArray(tokin), condition); } public static List jfind_preprocess(List tok) { for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">")); replaceSublist(tok, ll("\\", "", "*"), ll("\\*")); return tok; } public static HashSet lithashset(A... items) { HashSet set = new HashSet(); for (A a : items) set.add(a); return set; } public static boolean checkTokCondition(Object condition, List tok, int i) { if (condition instanceof TokCondition) return ((TokCondition) condition).get(tok, i); return checkCondition(condition, tok, i); } public static void replaceCollection(Collection dest, Collection src) { dest.clear(); dest.addAll(src); } public static void replaceListPart(List l, int i, int j, List l2) { int j2 = i + l(l2); if (j2 == j) { copyListPart(l2, 0, l, i, l(l2)); return; } l.subList(i, j).clear(); l.addAll(i, l2); } public static List mechList_opt_tlft(String name) { return tlft(mechList_opt_raw(name)); } public static List dropFirstThreeAndLastThree(List l) { return dropFirstAndLast(3, l); } public static int findEndOfCurlyBracketPart(List cnc, int i) { int j = i + 2, level = 1; while (j < cnc.size()) { if (eq(cnc.get(j), "{")) ++level; else if (eq(cnc.get(j), "}")) --level; if (level == 0) return j + 1; ++j; } return cnc.size(); } public static boolean isStaticMethod(Method m) { return methodIsStatic(m); } public 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; } public static void listThreadLocalAdd(ThreadLocal> tl, A a) { List l = tl.get(); if (l == null) tl.set(l = new ArrayList()); l.add(a); } public static A listThreadLocalPopLast(ThreadLocal> tl) { List l = tl.get(); if (l == null) return null; A a = popLast(l); if (empty(l)) tl.set(null); return a; } public static void removeSubList(List l, int from, int to) { if (l != null) subList(l, from, to).clear(); } public static void removeSubList(List l, int from) { if (l != null) subList(l, from).clear(); } public static Object vmBus_query(String msg, Object... args) { Object arg = empty(args) ? null : l(args) == 1 ? args[0] : args; { Object __164 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg); if (__164 != null) return __164; } return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg); } public static Object vmBus_query(String msg) { return vmBus_query(msg, (Object) null); } public static Object dm_os() { { Object __104 = vm_generalMap_get("stefansOS"); if (__104 != null) return __104; } return creator(); } public static Method findMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args); } public 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; } public static String getTranspiledStandardFunctionsIfCached(TreeSet functionSet) { try { File f = transpiledStandardFunctions_file(functionSet); return loadTextFile(f); } catch (Throwable __e) { return null; } } public static boolean standardFunctionsCacheUpToDate(TreeSet functionSet) { File f = transpiledStandardFunctions_file(functionSet); long date = recommendedTranspilationDateForStandardFunctions(functionSet); return date != 0 && f.lastModified() >= date; } public static String joinWithPlus(Collection c) { return join("+", c); } public static String joinWithPlus(String... c) { return join("+", c); } public static Class veryQuickJava_finish(String src, List libs) { libs = cloneList(libs); src = findTranslators2(src, libs); String dehlibs = join(" ", libs); File bytecode = null; bytecode = javaCompile_overInternalBot(src, dehlibs); return hotwireCore(concatLists(ll(bytecode), loadLibraries(libs))); } public static boolean loadFunctions_debug; public static Object loadFunctions_veryQuickJava; public static Class loadFunctions(String... functions) { return loadFunctions(asList(functions)); } public static Class loadFunctions(Collection functions) { print("Compiling " + joinWithPlus(functions)); TreeSet functionSet = new TreeSet(functions); StringBuilder buf = new StringBuilder(); for (String s : functionSet) buf.append("please include function " + assertIdentifier(s) + ".\n"); long time = sysNow(); Class c; if (loadFunctions_veryQuickJava != null) c = (Class) callF(loadFunctions_veryQuickJava, str(buf)); else { veryQuickJava_transpiled.set(""); c = veryQuickJava(str(buf)); saveTranspiledStandardFunctions(functionSet, getAndClearThreadLocal(veryQuickJava_transpiled)); } if (loadFunctions_debug) done2_always(time, "loadFunctions: " + join(" ", functions)); return c; } public static int methodApplicabilityScore(Method m, Object[] args) { Class[] types = m.getParameterTypes(); if (types.length != args.length) return Integer.MAX_VALUE; int score = 0; for (int i = 0; i < types.length; i++) { Object a = args[i]; Class c = types[i]; if (a == null) ++score; else if (c == a.getClass()) { } else if (isInstanceX(c, a)) ++score; else return Integer.MAX_VALUE; } return score; } public static RuntimeException todo() { throw new RuntimeException("TODO"); } public static RuntimeException todo(String msg) { throw new RuntimeException("TODO: " + msg); } public static char firstChar(String s) { return s.charAt(0); } public static Class hotwire(String src) { assertFalse(_inCore()); Class j = getJavaX(); if (isAndroid()) { synchronized (j) { List libraries = new ArrayList(); File srcDir = (File) call(j, "transpileMain", src, libraries); if (srcDir == null) throw fail("transpileMain returned null (src=" + quote(src) + ")"); Object androidContext = get(j, "androidContext"); return (Class) call(j, "loadx2android", srcDir, src); } } else { Class c = (Class) (call(j, "hotwire", src)); hotwire_copyOver(c); return c; } } public static A callMain(A c, String... args) { callOpt(c, "main", new Object[] { args }); return c; } public static void callMain() { callMain(mc()); } public static File programDir_mine; public static File programDir() { return programDir(getProgramID()); } public static File programDir(String snippetID) { boolean me = sameSnippetID(snippetID, programID()); if (programDir_mine != null && me) return programDir_mine; File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID)); if (me) { String c = caseID(); if (nempty(c)) dir = newFile(dir, c); } return dir; } public static File programDir(String snippetID, String subPath) { return new File(programDir(snippetID), subPath); } public static File computerIDFile() { return javaxDataDir("Basic Info/computer-id.txt"); } public static File saveTextFile(String fileName, String contents) throws IOException { CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)"); try { File file = new File(fileName); mkdirsForFile(file); String tempFileName = fileName + "_temp"; File tempFile = new File(tempFileName); if (contents != null) { if (tempFile.exists()) try { String saveName = tempFileName + ".saved." + now(); copyFile(tempFile, new File(saveName)); } catch (Throwable e) { printStackTrace(e); } FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath()); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8"); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); } if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (contents != null) if (!tempFile.renameTo(file)) throw new IOException("Can't rename " + tempFile + " to " + file); vmBus_send("wroteFile", file); return file; } finally { action.done(); } } public static File saveTextFile(File fileName, String contents) { try { saveTextFile(fileName.getPath(), contents); return fileName; } catch (Exception __e) { throw rethrow(__e); } } public static File mkdirsForFile(File file) { File dir = file.getParentFile(); if (dir != null) { dir.mkdirs(); if (!dir.isDirectory()) if (dir.isFile()) throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!"); else throw fail("Unknown IO exception during mkdirs of " + f2s(file)); } return file; } public static String mkdirsForFile(String path) { mkdirsForFile(new File(path)); return path; } public static String getCanonicalPath(String path) { try { return new File(path).getCanonicalPath(); } catch (Exception __e) { throw rethrow(__e); } } public static FileOutputStream newFileOutputStream(File path) throws IOException { return newFileOutputStream(path.getPath()); } public static FileOutputStream newFileOutputStream(String path) throws IOException { return newFileOutputStream(path, false); } public static FileOutputStream newFileOutputStream(File path, boolean append) throws IOException { return newFileOutputStream(path.getPath(), append); } public static FileOutputStream newFileOutputStream(String path, boolean append) throws IOException { mkdirsForFile(path); FileOutputStream f = new FileOutputStream(path, append); _registerIO(f, path, true); return f; } public static AutoCloseable tempCleaningUp() { return tempSetTL(ping_isCleanUpThread, true); } public static void closeAllWriters(Collection l) { for (Writer w : unnull(l)) { try { w.close(); } catch (Throwable __e) { _handleException(__e); } } } public static JTextArea jTextAreaWithUndo() { return jTextAreaWithUndo(""); } public static JTextArea jTextAreaWithUndo(final String text) { return jenableUndoRedo(swingNu(JTextArea.class, text)); } public static boolean containsNewLines(String s) { return containsNewLine(s); } public static String jlabel_textAsHTML_center(String text) { return "
" + replace(htmlencode(text), "\n", "
") + "
"; } public static String getSelectedItem(JList l) { return (String) l.getSelectedValue(); } public static String getSelectedItem(JComboBox cb) { return strOrNull(cb.getSelectedItem()); } public static File localSnippetsDir() { return javaxDataDir("Personal Programs"); } public static File localSnippetsDir(String sub) { return newFile(localSnippetsDir(), sub); } public static String getOneLineFileInfoField(File f, String field) { File infoFile = associatedInfosFile(f); List lines = lines(loadTextFile(infoFile)); return firstStartingWithIC_drop(lines, field + ": "); } public static File fileInSameDir(File f, String newName) { return newFile(parentFile(f), newName); } public static
List takeFirst(List l, int n) { return l(l) <= n ? l : newSubListOrSame(l, 0, n); } public static List takeFirst(int n, List l) { return takeFirst(l, n); } public static String takeFirst(int n, String s) { return substring(s, 0, n); } public static String takeFirst(String s, int n) { return substring(s, 0, n); } public static List takeFirst(int n, Iterable i) { List l = new ArrayList(); Iterator it = i.iterator(); for (int _repeat_935 = 0; _repeat_935 < n; _repeat_935++) { if (it.hasNext()) l.add(it.next()); else break; } return l; } public static String makePostData(Map map) { List l = new ArrayList(); for (Map.Entry e : map.entrySet()) { String key = (String) (e.getKey()); Object val = e.getValue(); if (val != null) { String value = str(val); l.add(urlencode(key) + "=" + urlencode((value))); } } return join("&", l); } public static String makePostData(Object... params) { return makePostData(litorderedmap(params)); } public static volatile boolean muricaPassword_pretendNotAuthed; public static String muricaPassword() { if (muricaPassword_pretendNotAuthed) return null; return trim(loadTextFile(muricaPasswordFile())); } public static String standardCredentialsUser() { return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-username"), userDir(".tinybrain/username")))); } public static String standardCredentialsPass() { return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-userpass"), userDir(".tinybrain/userpass")))); } public static String urlencode(String x) { try { return URLEncoder.encode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static File DiskSnippetCache_file(long snippetID) { return new File(getGlobalCache(), "data_" + snippetID + ".jar"); } public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException { File file = DiskSnippetCache_file(snippetID); return file.exists() ? file : null; } public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException { saveBinaryFile(DiskSnippetCache_file(snippetID), data); } public static byte[] loadDataSnippetImpl(String snippetID) throws IOException { byte[] data; try { URL url = new URL(dataSnippetLink(snippetID)); print("Loading library: " + hideCredentials(url)); try { data = loadBinaryPage(url.openConnection()); } catch (RuntimeException e) { data = null; } if (data == null || data.length == 0) { url = new URL("http://data.tinybrain.de/blobs/" + parseSnippetID(snippetID)); print("Loading library: " + hideCredentials(url)); data = loadBinaryPage(url.openConnection()); } print("Bytes loaded: " + data.length); } catch (FileNotFoundException e) { throw new IOException("Binary snippet #" + snippetID + " not found or not public"); } return data; } public static long fileSize(String path) { return getFileSize(path); } public static long fileSize(File f) { return getFileSize(f); } public static File loadDataSnippetToFile(String snippetID) { try { snippetID = fsI(snippetID); File f = DiskSnippetCache_file(parseSnippetID(snippetID)); List urlsTried = new ArrayList(); List errors = new ArrayList(); try { URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID))); print("Loading library: " + hideCredentials(url)); try { loadBinaryPageToFile(openConnection(url), f); if (fileSize(f) == 0) throw fail(); } catch (Throwable e) { errors.add(e); url = addAndReturn(urlsTried, new URL("http://data.tinybrain.de/blobs/" + psI(snippetID))); print("Trying other server: " + hideCredentials(url)); loadBinaryPageToFile(openConnection(url), f); print("Got bytes: " + fileSize(f)); } if (fileSize(f) == 0) throw fail(); System.err.println("Bytes loaded: " + fileSize(f)); } catch (Throwable e) { printStackTrace(e); errors.add(e); throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors)); } return f; } catch (Exception __e) { throw rethrow(__e); } } public static byte[] isGIF_magic = bytesFromHex("47494638"); public static boolean isGIF(byte[] data) { return byteArrayStartsWith(data, isGIF_magic); } public static boolean isGIF(File f) { return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic))); } public static String f2s(File f) { return f == null ? null : f.getAbsolutePath(); } public static String f2s(java.nio.file.Path p) { return p == null ? null : f2s(p.toFile()); } public static void setVar(IVar v, A value) { if (v != null) v.set(value); } public static boolean checkCondition(Object condition, Object... args) { return isTrue(callF(condition, args)); } public static void copyListPart(List a, int i1, List b, int i2, int n) { if (a == null || b == null) return; for (int i = 0; i < n; i++) b.set(i2 + i, a.get(i1 + i)); } public static String mechList_opt_raw(String name) { try { Lock __974 = mechList_raw_lock; lock(__974); try { if (mechList_goToCreator() || eq(mechMode().readMode, "creator")) return (String) call(creator(), "mechList_opt_raw", name); String src = mechList_raw_cache.get(name); if (src != null) return src; src = mechList_opt_raw_fresh(name); mechList_raw_cache.put(name, unnull(src)); return src; } finally { unlock(__974); } } catch (Exception __e) { throw rethrow(__e); } } public static void _onLoad_mechList_opt_raw() { _registerAutoCloseable(vmBus_onMessage("mechList_clearCache", new VF1() { public void get(String listName) { try { if (!isTrue(mechList_clearCache_inFunction.get())) mechList_clearCache_noSend(listName); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!isTrue(mechList_clearCache_inFunction!))\r\n mechList_clearCache_noSe..."; } })); } public static List dropFirstAndLast(int n, List l) { return new ArrayList(subList(l, n, l(l) - n)); } public static List dropFirstAndLast(List l) { return dropFirstAndLast(1, l); } public static String dropFirstAndLast(String s) { return substring(s, 1, l(s) - 1); } public static boolean methodIsStatic(Method m) { return (m.getModifiers() & Modifier.STATIC) != 0; } public static boolean argumentCompatibleWithType(Object arg, Class type) { return arg == null ? !type.isPrimitive() : isInstanceX(type, arg); } public static A[] arrayOfType(Class type, int n) { return makeArray(type, n); } public static A[] arrayOfType(int n, Class type) { return arrayOfType(type, n); } public static ExpiringMap2 mechList_raw_cache = new ExpiringMap2(10000).setMap(ciMap()); public static Lock mechList_raw_lock = lock(); public static int mechList_raw_timeout = 60000; public static String mechList_raw(String name) { try { Lock __404 = mechList_raw_lock; lock(__404); try { if (empty(name)) return ""; String src = mechList_raw_cache.get(name); if (src != null) return src; AutoCloseable __405 = tempSetThreadLocal(loadPage_forcedTimeout_byThread, mechList_raw_timeout); try { src = mechList_raw_fresh(name); if (src != null) mechList_raw_cache.put(name, src); return src; } finally { _close(__405); } } finally { unlock(__404); } } catch (Exception __e) { throw rethrow(__e); } } public static VF2 mechList_raw_listener = new VF2() { public void get(String msg, Object arg) { try { if (eq(msg, "mechChange") && arg instanceof String) { mechList_raw_cache.remove((String) arg); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(msg, 'mechChange) && arg instanceof S) {\r\n //print(\"Got change noti..."; } }; public static void _onLoad_mechList_raw() { add(vm_busListeners_live(), mechList_raw_listener); } public static void cleanMeUp_mechList_raw() { remove(vm_busListeners_live(), mechList_raw_listener); } public static ThreadLocal mechList_clearCache_inFunction = new ThreadLocal(); public static void mechList_clearCache(String listName) { { AutoCloseable __980 = tempSetTL(mechList_clearCache_inFunction, true); try { print("Sending mech clear: " + listName); vmBus_send("mechList_clearCache", listName); } finally { _close(__980); } } mechList_clearCache_noSend(listName); } public static void mechList_clearCache_noSend(String listName) { for (String field : mcFields()) if (startsWithEndsWith(field, "mech", "_cache")) { Object o = getOptMC(field); if (o instanceof Map) removeFromMapCI_sync((Map) o, listName); } } public static Object pcallFAll_returnFirstNotNull(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) { Object __192 = pcallF(f, args); if (__192 != null) return __192; } return null; } public static Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) { while (it.hasNext()) { Object __193 = pcallF(it.next(), args); if (__193 != null) return __193; } return null; } public static Set vm_busListeners_live_cache; public static Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache; } public static Set vm_busListeners_live_load() { return vm_generalIdentityHashSet("busListeners"); } public static Map vm_busListenersByMessage_live_cache; public static Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache; } public static Map vm_busListenersByMessage_live_load() { return vm_generalHashMap("busListenersByMessage"); } public static File transpiledStandardFunctions_file(TreeSet functionSet) { String name = uniqueFileNameUsingMD5_80_v2(join("+", functionSet)); File dir = javaxCachesDir("Transpiled Standard Functions"); saveTextFileUnlessExists(newFile(dir, name + ".functions"), lines(functionSet)); return newFile(dir, name + ".java"); } public static long recommendedTranspilationDateForStandardFunctions(Collection sfNames) { long date = 0; for (String name : sfNames) { long d = recommendedTranspilationDateForStandardFunction(name); if (d == 0) return 0; date = max(date, d); } return date; } public static String findTranslators2(String src, List libsOut) { return join(findTranslators2(javaTok(src), libsOut)); } public static List findTranslators2(List tok, List libsOut) { int i; while ((i = jfind(tok, "!")) >= 0) { setAdd(libsOut, tok.get(i + 2)); clearTokens(tok, i, i + 3); } return tok; } public static File javaCompile_overInternalBot(String src) { return javaCompile_overInternalBot(src, ""); } public static synchronized File javaCompile_overInternalBot(String src, String dehlibs) { return CompilerBot.compile(src, dehlibs); } public static Class hotwireCore(List files) { try { JavaXClassLoader classLoader = hotwire_makeClassLoader(files); Class theClass = classLoader.loadClass("main"); setOpt(theClass, "__javax", getJavaX()); if (getOpt(theClass, "programID") == null) setOpt(theClass, "programID", "#3999999"); if (!_inCore()) hotwire_copyOver(theClass); return theClass; } catch (Exception __e) { throw rethrow(__e); } } public static List loadLibraries(List snippetIDs) { return map("loadLibrary", snippetIDs); } public static Class veryQuickJava(CharSequence mainJava) { return veryQuickJava3(str(mainJava)); } public static void saveTranspiledStandardFunctions(TreeSet functionSet, String transpiledSrc) { try { saveTextFile(transpiledStandardFunctions_file(functionSet), transpiledSrc); } catch (Throwable __e) { _handleException(__e); } } public static long done2_always(long startTime, String desc) { long time = sysNow() - startTime; print(desc + " [" + time + " ms]"); return time; } public static long done2_always(String desc, long startTime) { return done2_always(startTime, desc); } public static long done2_always(long startTime) { return done2_always(startTime, ""); } public static boolean _inCore() { return false; } public static List hotwire_copyOver_after = synchroList(); public static void hotwire_copyOver(Class c) { for (String field : ll("print_log", "print_silent", "androidContext", "_userHome")) setOptIfNotNull(c, field, getOpt(mc(), field)); setOptIfNotNull(c, "mainBot", getMainBot()); setOpt(c, "creator_class", new WeakReference(mc())); pcallFAll(hotwire_copyOver_after, c); } public static boolean sameSnippetID(String a, String b) { if (!isSnippetID(a) || !isSnippetID(b)) return false; return parseSnippetID(a) == parseSnippetID(b); } public static volatile String caseID_caseID; public static String caseID() { return caseID_caseID; } public static void caseID(String id) { caseID_caseID = id; } public static List beginCriticalAction_inFlight = synchroList(); public static class CriticalAction { public String description; public CriticalAction() { } public CriticalAction(String description) { this.description = description; } public void done() { beginCriticalAction_inFlight.remove(this); } } public static CriticalAction beginCriticalAction(String description) { ping(); CriticalAction c = new CriticalAction(description); beginCriticalAction_inFlight.add(c); return c; } public static void cleanMeUp_beginCriticalAction() { int n = 0; while (nempty(beginCriticalAction_inFlight)) { int m = l(beginCriticalAction_inFlight); if (m != n) { n = m; try { print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description"))); } catch (Throwable __e) { _handleException(__e); } } sleepInCleanUp(10); } } public static void copyFile(File src, File dest) { try { FileInputStream inputStream = new FileInputStream(src.getPath()); FileOutputStream outputStream = newFileOutputStream(dest.getPath()); try { copyStream(inputStream, outputStream); inputStream.close(); } finally { outputStream.close(); } } catch (Exception __e) { throw rethrow(__e); } } public static void vmBus_send(String msg, Object... args) { Object arg = empty(args) ? null : l(args) == 1 ? args[0] : args; pcallFAll(vm_busListeners_live(), msg, arg); pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg); } public static void vmBus_send(String msg) { vmBus_send(msg, (Object) null); } public static AutoCloseable tempSetTL(ThreadLocal tl, A a) { return tempSetThreadLocal(tl, a); } public static A jenableUndoRedo(final A textcomp) { { swing(new Runnable() { public void run() { try { final UndoManager undo = new UndoManager(); vm_generalWeakSet("Undo Managers").add(undo); textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent evt) { undo.addEdit(evt.getEdit()); } }); textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() { public void run() { try { if (undo.canUndo()) undo.undo(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canUndo()) undo.undo()"; } })); textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() { public void run() { try { if (undo.canRedo()) undo.redo(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canRedo()) undo.redo()"; } })); textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo"); textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new UndoManager undo;\r\n vm_generalWeakSet(\"Undo Managers\").add(undo)..."; } }); } return textcomp; } public static A swingNu(final Class c, final Object... args) { return swingConstruct(c, args); } public static boolean containsNewLine(String s) { return contains(s, '\n'); } public static List replace(List l, A a, A b) { for (int i = 0; i < l(l); i++) if (eq(l.get(i), a)) l.set(i, b); return l; } public static String replace(String s, String a, String b) { return s == null ? null : a == null || b == null ? s : s.replace(a, b); } public static String replace(String s, char a, char b) { return s == null ? null : s.replace(a, b); } public static String htmlencode(Object o) { return htmlencode(str(o)); } public static String htmlencode(String s) { if (s == null) return ""; StringBuilder out = new StringBuilder(Math.max(16, s.length())); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') out.append("&#").append((int) c).append(';'); else out.append(c); } return out.toString(); } public static String strOrNull(Object o) { return o == null ? null : str(o); } public static File associatedInfosFile(File f) { return replaceExtension(f, ".infos"); } public static String firstStartingWithIC_drop(Collection l, final String prefix) { for (String s : unnull(l)) if (swic(s, prefix)) return substring(s, l(prefix)); return null; } public static String firstStartingWithIC_drop(String prefix, Collection l) { return firstStartingWithIC_drop(l, prefix); } public static File parentFile(File f) { return dirOfFile(f); } public static List newSubListOrSame(List l, int startIndex) { return newSubListOrSame(l, startIndex, l(l)); } public static List newSubListOrSame(List l, int startIndex, int endIndex) { if (l == null) return null; int n = l(l); startIndex = max(0, startIndex); endIndex = min(n, endIndex); if (startIndex >= endIndex) return ll(); if (startIndex == 0 && endIndex == n) return l; return cloneList(l.subList(startIndex, endIndex)); } public static LinkedHashMap litorderedmap(Object... x) { LinkedHashMap map = new LinkedHashMap(); litmap_impl(map, x); return map; } public static File muricaPasswordFile() { return new File(javaxSecretDir(), "murica/muricaPasswordFile"); } public static File oneOfTheFiles(String... paths) { if (paths != null) for (String path : paths) if (fileExists(path)) return newFile(path); return null; } public static File oneOfTheFiles(File... files) { if (files != null) for (File f : files) if (fileExists(f)) return f; return null; } public static File javaxSecretDir_dir; public static File javaxSecretDir() { return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret"); } public static File javaxSecretDir(String sub) { return newFile(javaxSecretDir(), sub); } public static File getGlobalCache() { File file = new File(javaxCachesDir(), "Binary Snippets"); file.mkdirs(); return file; } public static byte[] saveBinaryFile(String fileName, byte[] contents) { try { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = newFileOutputStream(tempFileName); fileOutputStream.write(contents); fileOutputStream.close(); if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); vmBus_send("wroteFile", file); return contents; } catch (Exception __e) { throw rethrow(__e); } } public static byte[] saveBinaryFile(File fileName, byte[] contents) { return saveBinaryFile(fileName.getPath(), contents); } public static String dataSnippetLink(String snippetID) { long id = parseSnippetID(snippetID); if (id >= 1100000 && id < 1200000) return imageServerURL() + id; if (id >= 1400000 && id < 1500000) return "http://butter.botcompany.de:8080/files/" + id + "?_pass=" + muricaPassword(); if (id >= 1200000 && id < 1300000) { String pw = muricaPassword(); if (empty(pw)) throw fail("Please set 'murica password by running #1008829"); return "http://butter.botcompany.de:8080/1008823/raw/" + id + "?_pass=" + pw; } else return "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id + "&contentType=application/binary"; } public static ThreadLocal>> loadBinaryPage_responseHeaders = new ThreadLocal(); public static ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal(); public static byte[] loadBinaryPage(String url) { try { print("Loading " + url); return loadBinaryPage(loadPage_openConnection(new URL(url))); } catch (Exception __e) { throw rethrow(__e); } } public static byte[] loadBinaryPage(URLConnection con) { try { Map extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders); setHeaders(con); for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key)); return loadBinaryPage_noHeaders(con); } catch (Exception __e) { throw rethrow(__e); } } public static byte[] loadBinaryPage_noHeaders(URLConnection con) { try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); InputStream inputStream = con.getInputStream(); loadBinaryPage_responseHeaders.set(con.getHeaderFields()); long len = 0; try { len = con.getContentLength(); } catch (Throwable e) { printStackTrace(e); } int n = 0; while (true) { int ch = inputStream.read(); if (ch < 0) break; buf.write(ch); if (++n % 100000 == 0) println(" " + n + (len != 0 ? "/" + len : "") + " bytes loaded."); } inputStream.close(); return buf.toByteArray(); } catch (Exception __e) { throw rethrow(__e); } } public static A addAndReturn(Collection c, A a) { if (c != null) c.add(a); return a; } public static void loadBinaryPageToFile(String url, File file) { try { print("Loading " + url); loadBinaryPageToFile(openConnection(new URL(url)), file); } catch (Exception __e) { throw rethrow(__e); } } public static void loadBinaryPageToFile(URLConnection con, File file) { try { setHeaders(con); loadBinaryPageToFile_noHeaders(con, file); } catch (Exception __e) { throw rethrow(__e); } } public static void loadBinaryPageToFile_noHeaders(URLConnection con, File file) { try { File ftemp = new File(f2s(file) + "_temp"); FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp)); try { InputStream inputStream = con.getInputStream(); long len = 0; try { len = con.getContentLength(); } catch (Throwable e) { printStackTrace(e); } String pat = " {*}" + (len != 0 ? "/" + len : "") + " bytes loaded."; copyStreamWithPrints(inputStream, buf, pat); inputStream.close(); buf.close(); file.delete(); renameFile_assertTrue(ftemp, file); } finally { if (buf != null) buf.close(); } } catch (Exception __e) { throw rethrow(__e); } } public static byte[] bytesFromHex(String s) { return hexToBytes(s); } public static boolean byteArrayStartsWith(byte[] a, byte[] b) { if (a == null || b == null) return false; if (a.length < b.length) return false; for (int i = 0; i < b.length; i++) if (a[i] != b[i]) return false; return true; } public static byte[] loadBeginningOfBinaryFile(File file, int maxBytes) { return loadBinaryFilePart(file, 0, maxBytes); } public static boolean mechList_goToCreator_dont; public static boolean mechList_goToCreator() { return eqOneOf(mechMode().readMode, null, "creator") && !mechList_goToCreator_dont && hasMethodNamed(creator(), "mechList_opt_raw"); } public static MechMode mechMode_value = new MechMode(); public static MechMode mechMode() { return mechMode_value; } public static String mechList_opt_raw_fresh(String name) { Object readMode = mechMode().readMode; if (readMode instanceof File) { String md5Name = uniqueFileNameUsingMD5_80_v2(upper(name)); return loadTextFileFromZipFile((File) readMode, md5Name); } boolean useLocal = false, useRemote = true; if (eq(readMode, "mergeLocalAndRemote")) useLocal = true; else if (eq(readMode, "local")) { useLocal = true; useRemote = false; } String s = ""; if (useRemote) { if (eq(mechMode().readMode, "localCopies")) s = unnull(loadTextFile(remoteMechListMirrorFile(name))); else s = serverMechList_raw_fresh(name, true); } if (useLocal) s = appendNewLineIfNempty(s) + localMechList_opt_raw_fresh(name); return s; } public static Set _registerAutoCloseable_set = synchroHashSet(); public static void _registerAutoCloseable(AutoCloseable c) { addIfNotNull(_registerAutoCloseable_set, c); } public static void cleanMeUp__registerAutoCloseable() { closeAutoCloseables(getAndClearList(_registerAutoCloseable_set)); } public static AutoCloseable vmBus_onMessage(final String msg, final VF1 onMessage) { Map map = vm_busListenersByMessage_live(); synchronized (map) { Set listeners = map.get(msg); if (listeners == null) map.put(msg, listeners = syncIdentityHashSet()); return tempAdd(listeners, new VF2() { public void get(String _msg, Object arg) { try { callF(onMessage, arg); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage, arg)"; } }); } } public static AutoCloseable vmBus_onMessage(String msg, final VF2 onMessage) { return vmBus_onMessage(msg, new VF1() { public void get(Object[] o) { try { callF(onMessage, first(o), second(o)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage, first(o), second(o));"; } }); } public static AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) { return vmBus_onMessage(msg, runnableToVF1(onMessage)); } public static A[] makeArray(Class type, int n) { return (A[]) Array.newInstance(type, n); } public static File loadLibrary(String snippetID) { return loadBinarySnippet(snippetID); } public static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) { if (tl == null) return null; final A prev = setThreadLocal(tl, a); return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); } }; } public static String mechList_raw_fresh(String name) { return mechList_opt_raw_fresh(name); } public static void add(BitSet bs, int i) { bs.set(i); } public static boolean add(Collection c, A a) { return c != null && c.add(a); } public static void add(Container c, Component x) { addToContainer(c, x); } public static void remove(List l, int i) { if (l != null && i >= 0 && i < l(l)) l.remove(i); } public static void remove(Collection l, A a) { if (l != null) l.remove(a); } public static Set mcFields() { return staticFieldNames(mc()); } public static boolean startsWithEndsWith(String s, String prefix, String suffix) { return startsWith(s, prefix) && endsWith(s, suffix); } public static Object getOptMC(String field) { return getOpt(mc(), field); } public static void removeFromMapCI_sync(Map map, String key) { if (map == null) return; synchronized (getMutex(map)) { for (String k : cloneList(keys(map))) if (eqic(key, k)) map.remove(k); } } public 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; } } public 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; } } public static String uniqueFileNameUsingMD5_80_v2(String fullName) { return uniqueFileNameUsingMD5_80_v2(fullName, md5(fullName)); } public static String uniqueFileNameUsingMD5_80_v2(String fullName, String md5) { return takeFirst(80 - 33, fileNameEncode(fullName)) + " - " + md5; } public static void saveTextFileUnlessExists(File f, String contents) { if (f != null && !f.exists()) saveTextFile(f, contents); } public static long recommendedTranspilationDateForStandardFunction(String sfName) { return toLong(mechMap("Recommended SF Transpilation Date").get(sfName)); } public static boolean setAdd(Collection c, A a) { if (c == null || c.contains(a)) return false; c.add(a); return true; } public static void clearTokens(List tok) { clearAllTokens(tok); } public static void clearTokens(List tok, int i, int j) { clearAllTokens(tok, i, j); } public static JavaXClassLoader hotwire_makeClassLoader(List files) { Collection toShare = hotwire_classesToShare(); return nempty(toShare) ? new JavaXClassLoaderWithParent2(null, files, myClassLoader(), cloneList(toShare)) : new JavaXClassLoader(null, files); } public static boolean veryQuickJava_silent = true; public static boolean veryQuickJava_useCompilerBot = true; public static ThreadLocal veryQuickJava_transpiled = new ThreadLocal(); public static Object veryQuickJava3_cacheFunction; public static Class veryQuickJava3(String mainJava) { return veryQuickJava3(mainJava, emptyList()); } public static Class veryQuickJava3(String mainJava, List libs) { Class c = (Class) (callF(veryQuickJava3_cacheFunction, mainJava, libs)); if (c != null) return c; transpileRaw_silent = veryQuickJava_silent; String src = transpileRaw(mainJava); if (veryQuickJava_transpiled.get() != null) veryQuickJava_transpiled.set(src); return veryQuickJava_finish(src, libs); } public static void setOptIfNotNull(Object o, String field, Object value) { if (value != null) setOpt(o, field, value); } public static Object mainBot; public static Object getMainBot() { return mainBot; } public static void sleepInCleanUp(long ms) { try { if (ms < 0) return; Thread.sleep(ms); } catch (Exception __e) { throw rethrow(__e); } } public static void copyStream(InputStream in, OutputStream out) { try { byte[] buf = new byte[65536]; while (true) { int n = in.read(buf); if (n <= 0) return; out.write(buf, 0, n); } } catch (Exception __e) { throw rethrow(__e); } } public static Set vm_generalWeakSet(Object name) { synchronized (get(javax(), "generalMap")) { Set set = (Set) (vm_generalMap_get(name)); if (set == null) vm_generalMap_put(name, set = newWeakHashSet()); return set; } } public static File replaceExtension(File f, String extOld, String extNew) { return newFile(replaceExtension(f2s(f), extOld, extNew)); } public static File replaceExtension(File f, String extNew) { return replaceExtension(f, fileExtension(f), extNew); } public static String replaceExtension(String s, String extOld, String extNew) { s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s); return s + addPrefixOptIfNempty(".", extNew); } public static String replaceExtension(String name, String extNew) { return replaceExtension(name, fileExtension(name), extNew); } public static File dirOfFile(File f) { return f == null ? null : f.getParentFile(); } public static boolean fileExists(String path) { return path != null && new File(path).exists(); } public static boolean fileExists(File f) { return f != null && f.exists(); } public static A println(A a) { return print(a); } public static File mkdirsFor(File file) { return mkdirsForFile(file); } public static void copyStreamWithPrints(InputStream in, OutputStream out, String pat) { try { byte[] buf = new byte[65536]; int total = 0; while (true) { int n = in.read(buf); if (n <= 0) return; out.write(buf, 0, n); if ((total + n) / 100000 > total / 100000) print(pat.replace("{*}", str(roundDownTo(total, 100000)))); total += n; } } catch (Exception __e) { throw rethrow(__e); } } public static void renameFile_assertTrue(File a, File b) { try { if (!a.exists()) throw fail("Source file not found: " + f2s(a)); if (b.exists()) throw fail("Target file exists: " + f2s(b)); mkdirsForFile(b); if (!a.renameTo(b)) throw fail("Can't rename " + f2s(a) + " to " + f2s(b)); } catch (Exception __e) { throw rethrow(__e); } } public static byte[] loadBinaryFilePart(File file, long start, long end) { try { RandomAccessFile raf = new RandomAccessFile(file, "r"); int n = toInt(min(raf.length(), end - start)); byte[] buffer = new byte[n]; try { raf.seek(start); raf.readFully(buffer, 0, n); return buffer; } finally { raf.close(); } } catch (Exception __e) { throw rethrow(__e); } } public static boolean hasMethodNamed(Object obj, String method) { if (obj == null) return false; if (obj instanceof Class) return hasMethodNamed((Class) obj, method); return hasMethodNamed(obj.getClass(), method); } public static boolean hasMethodNamed(Class c, String method) { while (c != null) { for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) return true; c = c.getSuperclass(); } return false; } public static String upper(String s) { return s == null ? null : s.toUpperCase(); } public static char upper(char c) { return Character.toUpperCase(c); } public static String loadTextFileFromZipFile(File inZip, String fileName) { try { if (!fileExists(inZip)) return null; try { ZipFile zip = new ZipFile(inZip); try { return loadTextFileFromZipFile(zip, fileName); } finally { _close(zip); } } catch (Throwable e) { throw fail(f2s(inZip), e); } } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFileFromZipFile(ZipFile zip, String fileName) { try { ZipEntry entry = zip.getEntry(fileName); if (entry == null) return null; InputStream fin = zip.getInputStream(entry); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copyStream(fin, baos); return fromUTF8(baos.toByteArray()); } finally { _close(fin); } } catch (Exception __e) { throw rethrow(__e); } } public static File remoteMechListMirrorFile(String listName) { return newFile(remoteMechListMirrorsDir(), uniqueFileNameUsingMD5_80_v2(upper(listName))); } public static boolean serverMechList_raw_fresh_verbose; public static String serverMechList_raw_fresh(String name) { return serverMechList_raw_fresh(name, false); } public static String serverMechList_raw_fresh(String name, boolean opt) { Lock __834 = downloadLock(); lock(__834); try { String text = null; try { text = loadTextFile(remoteMechListMirrorFile(name)); } catch (Throwable __e) { _handleException(__e); } Object[] params = muricaCredentialsPlus("md5", md5OrNull(text), "l", l(text), "opt", opt ? 1 : 0, "withStatus", 1); String url = "http://butter.botcompany.de:8080/mech/raw/list-text/" + urlencode(name); String page = postPageSilently(url, params); Map map = jsonDecodeMap(page); boolean same = eq(map.get("Same"), true); boolean appended = eq(map.get("Appended"), true); saveTextFile(remoteMechListMirrorMetaFile(name), struct(getMultipleKeys(map, "Name", "Status"))); if (!same) { if (appended) text += (String) map.get("Text"); else text = (String) map.get("Text"); saveTextFile(remoteMechListMirrorFile(name), text); File nameFile = remoteMechListMirrorNameFile(name); if (!fileExists(nameFile)) { String actualName = or((String) map.get("Name"), name); saveTextFile(nameFile, actualName); } } if (serverMechList_raw_fresh_verbose) print("Mech list " + name + ": " + (appended ? "appended" : same ? "same" : "downloaded") + ": " + n2(countLines(text), "line")); if (!same) vmBus_send("remoteMechListMirrorChanged", name); return text; } finally { unlock(__834); } } public static String appendNewLineIfNempty(String s) { return empty(s) ? "" : s + "\n"; } public static String localMechList_opt_raw_fresh(String name) { return unnull(loadTextFile(localMechListFile(name))); } public static Set synchroHashSet() { return Collections.synchronizedSet(new HashSet()); } public static void addIfNotNull(Collection l, A a) { if (a != null && l != null) l.add(a); } public static void addIfNotNull(MultiSet ms, A a) { if (a != null && ms != null) ms.add(a); } public static void closeAutoCloseables(Collection l) { if (l != null) for (AutoCloseable c : l) { try { c.close(); } catch (Throwable __e) { _handleException(__e); } } } public static List getAndClearList(Collection l) { if (l == null) return emptyList(); synchronized (collectionMutex(l)) { List out = cloneList(l); l.clear(); return out; } } public static Set syncIdentityHashSet() { return (Set) synchronizedSet(identityHashSet()); } public static AutoCloseable tempAdd(final Collection l, final A a) { if (l == null || l.contains(a)) return null; l.add(a); return new AutoCloseable() { public String toString() { return "l.remove(a);"; } public void close() throws Exception { l.remove(a); } }; } public static A third(List l) { return _get(l, 2); } public static A third(A[] bla) { return bla == null || bla.length <= 2 ? null : bla[2]; } public static C third(T3 t) { return t == null ? null : t.c; } public static VF1 runnableToVF1(final Runnable r) { return r == null ? null : new VF1() { public void get(A a) { try { r.run(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "r.run()"; } }; } public static A setThreadLocal(ThreadLocal tl, A value) { if (tl == null) return null; A old = tl.get(); tl.set(value); return old; } public static void addToContainer(final Container a, final Component b) { if (a != null && b != null) { swing(new Runnable() { public void run() { try { a.add(b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.add(b);"; } }); } } public static Set staticFieldNames(Object o) { TreeSet fields = new TreeSet(); Class _c = _getClass(o); do { for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & Modifier.STATIC) != 0) fields.add(f.getName()); _c = _c.getSuperclass(); } while (_c != null); return fields; } public static Object getMutex(Object o) { return collectionMutex(o); } public static Map syncHashMap() { return synchroHashMap(); } public static String fileNameEncode_safeChars = " ()[]#,!"; public static String fileNameEncode(String s) { StringBuilder buf = new StringBuilder(); int n = l(s); for (int i = 0; i < n; i++) { char c = s.charAt(i); if (contains(fileNameEncode_safeChars, c)) buf.append(c); else buf.append(urlencode(str(c))); } return str(buf); } public static long toLong(Object o) { if (o instanceof Number) return ((Number) o).longValue(); if (o instanceof String) return parseLong((String) o); return 0; } public static Map mechMap(String listName) { return mechMapCI(listName); } public static Set hotwire_classesToShare = synchroSet(); public static Set hotwire_classesToShare() { return hotwire_classesToShare; } public static ClassLoader myClassLoader() { return _getClass(mc()).getClassLoader(); } public static boolean transpileRaw_silent = true; public static boolean transpileRaw_useDiskCache; public static Class transpileRaw_trans; public static boolean transpileRaw_verySilent; public static Lock transpileRaw_lock = lock(); public static String transpileRaw(String mainJava) { return transpileRaw(mainJava, false, transpileRaw_useDiskCache); } public static String transpileRaw(String mainJava, boolean fragment) { return transpileRaw(mainJava, fragment, transpileRaw_useDiskCache); } public static String transpileRaw(String mainJava, boolean fragment, boolean useDiskCache) { mainJava = dropTranslators(mainJava); transpileRaw_copyFromCreator(); Lock __238 = transpileRaw_lock; lock(__238); try { File cacheFile = null; if (useDiskCache) { cacheFile = new File(javaxCodeDir(), "Transpilations/" + uniqueFileNameUsingMD5_80_v2(mainJava) + ".java"); { String _a_245 = loadTextFile(cacheFile); if (!empty(_a_245)) return _a_245; } } { JWindow _loading_window = showLoadingAnimation("Transpiling..."); try { transpileRaw_translator(); if (fragment) setOpt(transpileRaw_trans, "localStuffOnly", true); set(transpileRaw_trans, "mainJava", mainJava); if (!transpileRaw_verySilent) print("Running translator " + getOpt(transpileRaw_trans, "programID")); callMain(transpileRaw_trans); String main = (String) (get(transpileRaw_trans, "mainJava")); if (useDiskCache) { saveTextFile(new File(cacheFile.getPath() + "x"), mainJava); saveTextFile(cacheFile, main); } return main; } finally { disposeWindow(_loading_window); } } } finally { unlock(__238); } } public static Class transpileRaw_translator() { if (transpileRaw_trans == null) { transpileRaw_trans = hotwireSharingLibraries_silently(defaultJavaXTranslatorID()); } setOpt(transpileRaw_trans, "print_silent", transpileRaw_silent); return transpileRaw_trans; } public static void transpileRaw_copyFromCreator() { Lock __239 = transpileRaw_lock; lock(__239); try { if (transpileRaw_trans != null) return; Object c = creator(); if (c == null) return; Class trans = (Class) (getOpt(c, "transpileRaw_trans")); Lock lock = (Lock) (getOpt(c, "transpileRaw_lock")); if (trans != null && lock != null) { print("Using creator's transpiler: " + getProgramID(c) + " => " + programID()); transpileRaw_lock = lock; transpileRaw_trans = trans; } } finally { unlock(__239); } } public static void cleanMeUp_transpileRaw() { transpileRaw_trans = null; } public static Set newWeakHashSet() { return synchroWeakHashSet(); } public static String fileExtension(File f) { if (f == null) return null; return fileExtension(f.getName()); } public static String fileExtension(String s) { return substring(s, smartLastIndexOf(s, '.')); } public static String dropSuffixIC(String suffix, String s) { return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s; } public static String addPrefixOptIfNempty(String prefix, String s) { return addPrefixIfNotEmpty2(prefix, s); } public static int roundDownTo(int x, int n) { return x / n * n; } public static long roundDownTo(long x, long n) { return x / n * n; } public static String fromUTF8(byte[] bytes) { return fromUtf8(bytes); } public static File remoteMechListMirrorsDir() { return javaxDataDir("Remote Mech Lists"); } public static Object[] muricaCredentialsPlus(Object... params) { return concatArrays(muricaCredentials(), params); } public static String md5OrNull(String s) { return s == null ? null : md5(s); } public static String postPageSilently(String url, Object... params) { return doPostSilently(litmap(params), url); } public static Map jsonDecodeMap(String s) { Object o = jsonDecode(s); if (o instanceof List && empty((List) o)) return new HashMap(); if (o instanceof Map) return (Map) o; else throw fail("Not a JSON map: " + s); } public static File remoteMechListMirrorMetaFile(String listName) { return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".meta"); } public static Map getMultipleKeys(Map map, A... keys) { Map map2 = similarEmptyMap(map); if (map != null) for (A key : keys) map2.put(key, map.get(key)); return map2; } public static File remoteMechListMirrorNameFile(String listName) { return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".name"); } public static int countLines(String s) { return l(toLines(s)); } public static File localMechListFile(String listName) { return newFile(localMechListsDir(), uniqueFileNameUsingMD5_80_v2(listName) + ".text"); } public static Set synchronizedSet() { return synchroHashSet(); } public static Set synchronizedSet(Set set) { return Collections.synchronizedSet(set); } public static Set identityHashSet() { return Collections.newSetFromMap(new IdentityHashMap()); } public static Map>> mechMapCI_cache = synchroMap(); public static Map mechMapCI(String listName) { Pair> p = mechMapCI_cache.get(listName); String text = mechList_raw(listName); if (p != null && eq(p.a, text)) return p.b; String parsing = first(mechList_opt(listName + " | Parsing")); Map map; if (parsing == null) map = parseDoubleArrowMapCI(tlft(text)); else map = asCIMap((Map) callAndMake(parsing, text)); p = pair(text, map); mechMapCI_cache.put(listName, p); return p.b; } public static Set synchroSet() { return synchroHashSet(); } public static Set synchroSet(Set set) { return Collections.synchronizedSet(set); } public static String dropTranslators(String src) { return findTranslators2(src, null); } public static List dropTranslators(List tok) { return findTranslators2(tok, null); } public static JWindow showLoadingAnimation() { return showLoadingAnimation("Hold on user..."); } public static JWindow showLoadingAnimation(String text) { try { return showAnimationInTopRightCorner("#1003543", text); } catch (Throwable __e) { return null; } } public static Class hotwireSharingLibraries_silently(String progID) { AutoCloseable __9 = tempSetThreadLocal(loadPage_silent, true); try { return hotwireSharingLibraries(progID); } finally { _close(__9); } } public static String defaultJavaXTranslatorID_value = "#759"; public static String defaultJavaXTranslatorID() { return defaultJavaXTranslatorID_value; } public static Set synchroWeakHashSet() { return Collections.newSetFromMap((Map) newWeakHashMap()); } public static String addPrefixIfNotEmpty2(String prefix, String s) { return empty(s) ? "" : addPrefix(prefix, s); } public static Object[] concatArrays(Object[]... arrays) { int l = 0; for (Object[] a : arrays) l += l(a); Object[] x = new Object[l]; int i = 0; for (Object[] a : arrays) if (a != null) { System.arraycopy(a, 0, x, i, l(a)); i += l(a); } return x; } public static String doPostSilently(Map urlParameters, String url) { return doPostSilently(makePostData(urlParameters), url); } public static String doPostSilently(String urlParameters, String url) { doPost_silently.set(true); return doPost(urlParameters, url); } public static boolean jsonDecode_useOrderedMaps = true; public static Object jsonDecode(final String text) { final List tok = jsonTok(text); if (l(tok) == 1) return null; class Y { public int i = 1; public Object parse() { String t = tok.get(i); if (t.startsWith("\"")) { String s = unquote(tok.get(i)); i += 2; return s; } if (t.equals("{")) return parseMap(); if (t.equals("[")) return this.parseList(); if (t.equals("null")) { i += 2; return null; } if (t.equals("false")) { i += 2; return false; } if (t.equals("true")) { i += 2; return true; } boolean minus = false; if (t.equals("-")) { minus = true; i += 2; t = get(tok, i); } if (isInteger(t)) { i += 2; if (eq(get(tok, i), ".")) { String x = t + "." + get(tok, i + 2); i += 4; double d = parseDouble(x); if (minus) d = -d; return d; } else { long l = parseLong(t); if (minus) l = -l; return l != (int) l ? new Long(l) : new Integer((int) l); } } throw new RuntimeException("Unknown token " + (i + 1) + ": " + t + ": " + text); } public Object parseList() { consume("["); List list = new ArrayList(); while (!tok.get(i).equals("]")) { list.add(parse()); if (tok.get(i).equals(",")) i += 2; } consume("]"); return list; } public Object parseMap() { consume("{"); Map map = jsonDecode_useOrderedMaps ? new LinkedHashMap() : new TreeMap(); while (!tok.get(i).equals("}")) { String key = unquote(tok.get(i)); i += 2; consume(":"); Object value = parse(); map.put(key, value); if (tok.get(i).equals(",")) i += 2; } consume("}"); return map; } public void consume(String s) { if (!tok.get(i).equals(s)) { String prevToken = i - 2 >= 0 ? tok.get(i - 2) : ""; String nextTokens = join(tok.subList(i, Math.min(i + 4, tok.size()))); throw fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")"); } i += 2; } } return new Y().parse(); } public static File localMechListsDir() { return javaxDataDir("Mech Lists"); } public static Map parseDoubleLeftArrowMapCI_tlft(String s) { return parseDoubleLeftArrowMapCI(tlft(s)); } public static Map parseDoubleArrowMapCI(List l) { return parseDoubleArrowMap((Map) ciMap(), l); } public static boolean showAnimationInTopRightCorner_alwaysOnTop = true; public static boolean showAnimationInTopRightCorner_on = true; public static JWindow showAnimationInTopRightCorner(String imageID, String text) { if (isHeadless() || !showAnimationInTopRightCorner_on) return null; return showAnimationInTopRightCorner(imageIcon(imageID), text); } public static JWindow showAnimationInTopRightCorner(final Image image, final String text) { if (image == null || isHeadless() || !showAnimationInTopRightCorner_on) return null; return showAnimationInTopRightCorner(imageIcon(image), text); } public static JWindow showAnimationInTopRightCorner(final ImageIcon imageIcon, final String text) { if (isHeadless() || !showAnimationInTopRightCorner_on) return null; return (JWindow) swingAndWait(new F0() { public Object get() { try { JLabel label = new JLabel(imageIcon); if (nempty(text)) { label.setText(text); label.setVerticalTextPosition(SwingConstants.BOTTOM); label.setHorizontalTextPosition(SwingConstants.CENTER); } final JWindow window = showInTopRightCorner(label); onClick(label, new Runnable() { public void run() { try { window.dispose(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispose()"; } }); if (showAnimationInTopRightCorner_alwaysOnTop) window.setAlwaysOnTop(true); return window; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JLabel label = new JLabel(imageIcon);\r\n if (nempty(text)) {\r\n label.s..."; } }); } public static JWindow showAnimationInTopRightCorner(final String imageID) { return showAnimationInTopRightCorner(imageID, ""); } public static JWindow showAnimationInTopRightCorner(String imageID, double seconds) { return showAnimationInTopRightCorner(imageID, "", seconds); } public static JWindow showAnimationInTopRightCorner(String imageID, String text, double seconds) { if (isHeadless()) return null; return disposeWindowAfter(iround(seconds * 1000), showAnimationInTopRightCorner(imageID, text)); } public static JWindow showAnimationInTopRightCorner(BufferedImage img, String text, double seconds) { return disposeWindowAfter(iround(seconds * 1000), showAnimationInTopRightCorner(img, text)); } public static Class hotwireSharingLibraries(String progID) { try { Pair p = CompilerBot.compileSnippet2(progID); File jar = p.a; assertTrue(f2s(jar), jar.isFile()); List files = ll(jar); String dehlibs = unnull(loadTextFileFromZip(jar, "libraries")); List myLibraries = myLibraryFiles(); Matcher matcher = Pattern.compile("\\d+").matcher(dehlibs); while (matcher.find()) { String libID = matcher.group(); File lib = loadLibrary(libID); if (myLibraries.contains(lib)) { } else { files.add(lib); } } JavaXClassLoaderWithParent classLoader = new JavaXClassLoaderWithParent(progID, files, myClassLoader()); return hotwire_finish(classLoader, progID, p.b); } catch (Exception __e) { throw rethrow(__e); } } public static String addPrefix(String prefix, String s) { return s.startsWith(prefix) ? s : prefix + s; } public static ThreadLocal doPost_silently = new ThreadLocal(); public static ThreadLocal doPost_timeout = new ThreadLocal(); public static String doPost(Map urlParameters, String url) { return doPost(makePostData(urlParameters), url); } public static String doPost(String urlParameters, String url) { try { URL _url = new URL(url); ping(); return doPost(urlParameters, _url.openConnection(), _url); } catch (Exception __e) { throw rethrow(__e); } } public static String doPost(String urlParameters, URLConnection conn, URL url) { try { boolean silently = isTrue(optParam(doPost_silently)); Long timeout = optParam(doPost_timeout); setHeaders(conn); int l = lUtf8(urlParameters); if (!silently) print("Sending POST request: " + hideCredentials(url) + " (" + l + " bytes)"); if (timeout != null) setURLConnectionTimeouts(conn, timeout); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", str(l)); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); writer.write(urlParameters); writer.flush(); loadPage_charset.set("UTF-8"); String contents = loadPage(conn, url, false); writer.close(); return contents; } catch (Exception __e) { throw rethrow(__e); } } public static List jsonTok(String s) { List tok = new ArrayList(); int l = l(s); int i = 0; while (i < l) { int j = i; char c; String cc; while (j < l) { c = s.charAt(j); cc = s.substring(j, Math.min(j + 2, l)); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (cc.equals("/*")) { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (cc.equals("//")) { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isLetter(c)) do ++j; while (j < l && Character.isLetter(s.charAt(j))); else if (Character.isDigit(c)) do ++j; while (j < l && Character.isDigit(s.charAt(j))); else ++j; tok.add(s.substring(i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } public static Map parseDoubleLeftArrowMapCI(List l) { return parseDoubleLeftArrowMap((Map) ciMap(), l); } public static Map parseDoubleArrowMap(Map map, List l) { for (String s : l) { List x = splitAtDoubleArrow_bothDirections(s); if (l(x) == 2) map.put(first(x), second(x)); } return map; } public static JWindow showInTopRightCorner(Component c) { JWindow w = new JWindow(); w.add(c); w.pack(); moveToTopRightCorner(w); w.setVisible(true); return w; } public static String loadTextFileFromZip(File inZip, String fileName) { return loadTextFileFromZipFile(inZip, fileName); } public static List myLibraryFiles() { return (List) get(myClassLoader(), "files"); } public static Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource) { return hotwire_finish(classLoader, progID, javaSource, "main"); } public static Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource, String mainClass) { try { Class theClass = classLoader.loadClass(mainClass); Class j = getJavaX(); setOpt(theClass, "myJavaSource_code", javaSource); synchronized (j) { call(j, "setVars", theClass, progID); callOpt(j, "addInstance", progID, theClass); } hotwire_copyOver(theClass); return theClass; } catch (Exception __e) { throw rethrow(__e); } } public static int lUtf8(String s) { return l(utf8(s)); } public static Map parseDoubleLeftArrowMap(Map map, List l) { for (String s : l) { List x = splitAtDoubleLeftArrow(s); if (l(x) == 2) map.put(second(x), first(x)); } return map; } public static List splitAtDoubleArrow_bothDirections(String s) { return splitAtDoubleArrow_bothDirections(javaTok(s)); } public static List splitAtDoubleArrow_bothDirections(List tok) { List l = splitAtDoubleArrow(tok); if (l(l) != 2) l = reversedList(splitAtDoubleLeftArrow(tok)); return l; } public static List splitAtDoubleLeftArrow(String s) { return splitAtDoubleLeftArrow(javaTok(s)); } public static List splitAtDoubleLeftArrow(List tok) { List l = new ArrayList(); int i = 0; while (i < l(tok)) { int j = indexOfSubList(tok, ll("<", "", "="), i); if (i >= l(tok)) break; if (j < 0) j = l(tok); l.add(trimJoin(tok.subList(i, j))); i = j + 3; } return l; } public static List reversedList(Collection l) { List x = cloneList(l); Collections.reverse(x); return x; } public static final class _MethodCache { public final Class c; public final HashMap> cache = new HashMap(); public _MethodCache(Class c) { this.c = c; _init(); } public void _init() { Class _c = c; while (_c != null) { for (Method m : _c.getDeclaredMethods()) multiMapPut(cache, m.getName(), makeAccessible(m)); _c = _c.getSuperclass(); } for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault()) multiMapPut(cache, m.getName(), makeAccessible(m)); } public 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); } } public 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); } } } public abstract static class VF1 { public abstract void get(A a); } public static class GazelleEvalContext { public RuleEngine2 engine; public Map dataByRule; public Set linesSet; public transient List onNewNode; public GazellePredictor predictor; public GazelleEvalContext() { gazelle_addSharedClasses(); } } public abstract static class VF2 { public abstract void get(A a, B b); } public static class Matches { public String[] m; public Matches() { } public Matches(String... m) { this.m = m; } public String get(int i) { return i < m.length ? m[i] : null; } public String unq(int i) { return unquote(get(i)); } public String fsi(int i) { return formatSnippetID(unq(i)); } public String fsi() { return fsi(0); } public String tlc(int i) { return unq(i).toLowerCase(); } public boolean bool(int i) { return "true".equals(unq(i)); } public String rest() { return m[m.length - 1]; } public int psi(int i) { return Integer.parseInt(unq(i)); } public String toString() { return "Matches(" + joinWithComma(quoteAll(asList(m))) + ")"; } } public static class GazelleTree { public List children; public GazelleTree parent; public double weight = 1, totalWeight; public String line, lineType; public String prediction, judgement; public RuleEngine2_MatchedRule mr; public boolean isSplitNode; public transient GazelleEvalContext ctx; public GazelleTree() { } public GazelleTree(String line) { this.line = line; } public GazelleTree(GazelleEvalContext ctx, String line) { this.line = line; this.ctx = ctx; } public String toString() { return (isSplitNode ? "[split] " : "") + line + appendSquareBracketed(joinWithComma(listPlusNempties(renderQualityElements(), ruleID()))); } public List renderQualityElements() { List l = new ArrayList(); addIfNempty(l, prediction); if (mr != null) { l.add(mr.qualitySum() + " / " + formatDouble(mr.relativeQuality(), 2)); if (mr.moreConditions()) l.add("unsatisfied"); } return l; } public List history() { List l = new ArrayList(); GazelleTree e = this; while (e != null) { l.add(e.line); e = e.parent; } return reversed(l); } public void add(GazelleTree child) { if (children == null) children = new ArrayList(); child.parent = this; child.setContext(ctx); children.add(child); } public void setContext(GazelleEvalContext ctx) { this.ctx = ctx; pcallFAll(ctx.onNewNode, this); _add(ctx.linesSet, line); } public RuleEngine2.Rule rule() { return mr == null ? null : mr.rule; } public String ruleID() { return rule() == null ? null : rule().globalID; } public Map varMap() { return mr == null ? null : mr.map; } public void flush() { if (mr != null) { mr.flush(); line = mr.outText(); } } public Collection ruleComments() { RuleEngine2.Rule rule = rule(); return rule == null ? null : rule.comments; } } public static class Var implements IVar { public A v; public Var() { } public Var(A v) { this.v = v; } public synchronized void set(A a) { if (v != a) { v = a; notifyAll(); } } public synchronized A get() { return v; } public synchronized boolean has() { return v != null; } public synchronized void clear() { v = null; } public String toString() { return str(get()); } } public abstract static interface GazellePredictor { public String get(GazelleEvalContext ctx, RuleEngine2_MatchedRule mr); } public abstract static class TokCondition { public abstract boolean get(List tok, int i); } public static class MultiMap { public Map> data = new HashMap>(); public MultiMap() { } public MultiMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); } public MultiMap(MultiMap map) { putAll(map); } public MultiMap(Map> data) { this.data = data; } public void put(A key, B value) { synchronized (data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); list.add(value); } } public void addAll(A key, Collection values) { synchronized (data) { putAll(key, values); } } public void addAllIfNotThere(A key, Collection values) { synchronized (data) { for (B value : values) setPut(key, value); } } public void setPut(A key, B value) { synchronized (data) { if (!containsPair(key, value)) put(key, value); } } public boolean containsPair(A key, B value) { synchronized (data) { return get(key).contains(value); } } public void putAll(A key, Collection values) { synchronized (data) { for (B value : values) put(key, value); } } public void removeAll(A key, Collection values) { synchronized (data) { for (B value : values) remove(key, value); } } public List get(A key) { synchronized (data) { List list = data.get(key); return list == null ? Collections.emptyList() : list; } } public List getActual(A key) { synchronized (data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); return list; } } public void clean(A key) { synchronized (data) { List list = data.get(key); if (list != null && list.isEmpty()) data.remove(key); } } public Set keySet() { synchronized (data) { return data.keySet(); } } public Set keys() { synchronized (data) { return data.keySet(); } } public void remove(A key) { synchronized (data) { data.remove(key); } } public void remove(A key, B value) { synchronized (data) { List list = data.get(key); if (list != null) { list.remove(value); if (list.isEmpty()) data.remove(key); } } } public void clear() { synchronized (data) { data.clear(); } } public boolean containsKey(A key) { synchronized (data) { return data.containsKey(key); } } public B getFirst(A key) { synchronized (data) { List list = get(key); return list.isEmpty() ? null : list.get(0); } } public void addAll(MultiMap map) { putAll(map); } public void putAll(MultiMap map) { synchronized (data) { for (A key : map.keySet()) putAll(key, map.get(key)); } } public int keysSize() { synchronized (data) { return l(data); } } public int size() { synchronized (data) { int n = 0; for (List l : data.values()) n += l(l); return n; } } public List reverseGet(B b) { synchronized (data) { List l = new ArrayList(); for (A key : data.keySet()) if (data.get(key).contains(b)) l.add(key); return l; } } public Map> asMap() { synchronized (data) { return cloneMap(data); } } public boolean isEmpty() { synchronized (data) { return data.isEmpty(); } } public List _makeEmptyList() { return new ArrayList(); } public Collection> allLists() { synchronized (data) { return new ArrayList(data.values()); } } public List allValues() { return concatLists(values(data)); } public Object mutex() { return data; } public String toString() { return "mm" + str(data); } } public static class RuleEngine2 { public static class SimplifyWithRule extends Rule { public transient Object _function; public boolean isSplitRule; public boolean callOnTree; public Object function() { if (_function == null) { gazelle_parseInstruction(this); assertNotNull(_function); } return _function; } } public abstract static class QuickCheck { public abstract boolean check(String input); } public static class CicQuickCheck extends QuickCheck { public String string; public boolean check(String input) { return cic(input, string); } } public static class Rule { public String globalID; public List in; public String out, outType; public List comments; public Set vars; public List insWithType; public transient List inputMassagers; public transient List checkerFunctions; public transient List matchers; public String text; public QuickCheck applicabilityQuickCheck; public String purpose; public Double qualityCutOff; public boolean avoidRecentlyUsedMappings; public List mapMassagers; public String asText() { if (l(in) > 1 && eq(last(in), out)) return join(" \n+ ", dropLast(in)) + " \n+=> " + out; return join(" \n+ ", in) + " \n=> " + out; } public void addMapMassager(Object massager) { if (massager != null) mapMassagers = addToOrCreateList(mapMassagers, massager); } public void setInputMassager(int i, Object massager) { inputMassagers = listSetWithCreate(inputMassagers, i, massager); } public void setMatcher(int i, Object matcher) { matchers = listSetWithCreate(matchers, i, matcher); } public void parseGeneralComments() { purpose = gazelle_purposeFromComments(comments); try { String s = matchAny_firstGroup("quality cutoff = *", comments); if (s != null) qualityCutOff = parseDouble(s); } catch (Throwable __e) { _handleException(__e); } avoidRecentlyUsedMappings = cic(comments, "avoid recently used mapping"); } } public int minScore = 50; public int maxLevel = 100, maxOutLines = 10000; public List rules = new ArrayList(); public boolean printMappings, printGroupedData, printRejectedVars; public Set facts = ciSet(); public transient F2 callFunctionOnString = new F2() { public Object get(String function, String s) { try { return callAndMake(function, s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callAndMake(function, s)"; } }; public boolean hasHelpers; public RuleEngine2() { } public RuleEngine2(List> rulesWithComments) { for (Pair p : unnull(rulesWithComments)) addRule(p.a, splitAtDoubleArrow_pair(p.a), p.b, null); } public void copyRulesFrom(RuleEngine2 engine) { if (engine == null) return; rules.addAll(engine.rules); hasHelpers = engine.hasHelpers; } public void addRules2(List> rulesWithCommentsAndID) { Matches m = new Matches(); for (T3 p : unnull(rulesWithCommentsAndID)) { Pair p2 = splitAtDoubleArrow_pair(p.a); if (p2 != null) { addRule(p.a, p2, p.b, p.c); continue; } SimplifyWithRule r = new SimplifyWithRule(); r.globalID = p.c; r.text = p.a; r.comments = lines(p.b); r.parseGeneralComments(); String s = p.a; gazelle_parseInstruction(r); if (r._function == null) continue; rules.add(r); } } public void addRule(String text, Pair rule, String comments, String globalID) { if (rule == null) return; rule = ai_rule_pair_expandPlusArrow(rule); List conditions = tok_splitAtPlusAtBeginningOfLine(rule.a); Rule r = new Rule(); r.globalID = globalID; r.text = text; r.comments = lines(comments); r.parseGeneralComments(); r.in = conditions; r.insWithType = map(conditions, new F1() { public TextAndType get(String s) { try { return new TextAndType(s, "standard"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "TextAndType(s, \"standard\")"; } }); for (int i = 0; i < l(r.in); i++) { String s = r.in.get(i); { if (!(endsWith(s, ""))) continue; } if (eq(s, "")) r.checkerFunctions = listSetWithCreate(r.checkerFunctions, i, new F1>() { public Map get(String s) { try { return nempty(s) ? litmap() : null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "nempty(s) ? litmap() : null"; } }); else if (jmatch("* says: ", javaTokWithBrackets(s))) { r.setInputMassager(i, new F1() { public String get(String s) { try { Matches m = new Matches(); return jMatchStart("* says:", javaTokWithBrackets(s), m) ? m.get(0) + " says: " : s; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new Matches m; ret jMatchStart(\"* says:\", javaTokWithBrackets(s), m) ? m.get(..."; } }); } } for (Matches m : getJMatches_all("expand *", r.comments)) if (isQuoted(m.get(0))) { final String var = m.unq(0); for (int i = 0; i < l(r.in); i++) r.setMatcher(i, new Object() { public Map get(List tokC, List tokI, RuleEngine2_MatchedRule matched) { if (eqic(nextToLast(tokC), var)) tokI = tok_groupLastTokensToMatchPattern(tokI, tokC); return zipTwoListsToCIMap_strict_withoutEquals(tokC, tokI); } }); } if (jmatchAny(ll("in = dialog", "fact + event => replacement fact"), r.comments)) for (int i = 0; i < l(r.insWithType); i++) r.insWithType.get(i).type = "dialog-" + (l(r.insWithType) - i); Matches m = new Matches(); for (String s : r.comments) { if (jMatchStart("in * =", s, m) && isInteger(m.unq(0)) && startsWith(m.unq(1), "statement")) set(get(r.insWithType, parseInt(m.unq(0)) - 1), "type", m.unq(1)); if (jMatchStart("out = ", s, m)) r.outType = m.rest(); } r.out = rule.b; r.vars = ai_wordsInBothSidesOfPair_uncurly(rule); rules.add(r); } public List, String>> rulesAsPairs() { return map(rules, new F1, String>>() { public Pair, String> get(Rule r) { try { return pair(r.in, r.out); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pair(r.in, r.out)"; } }); } public List splitterRules() { return (List) filter(rules, new F1() { public Boolean get(Rule r) { try { return r instanceof SimplifyWithRule && ((SimplifyWithRule) r).isSplitRule; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "r instanceof SimplifyWithRule && ((SimplifyWithRule) r).isSplitRule"; } }); } public void dropRulesWhere(IF1 pred) { rules = antiFilter(pred, rules); } public void deleteRule(String ruleID) { dropRulesWhere(r -> eq(r.globalID, ruleID)); } public Rule getRule(String ruleID) { return firstWhere(rules, "globalID", ruleID); } } public static class Lowest { public A best; public double score; public transient Object onChange; public synchronized boolean isNewBest(double score) { return best == null || score < this.score; } public synchronized double bestScore() { return best == null ? Double.NaN : score; } public double score() { return bestScore(); } public synchronized float floatScore() { return best == null ? Float.NaN : (float) score; } public synchronized float floatScoreOr(float defaultValue) { return best == null ? defaultValue : (float) score; } public boolean put(A a, double score) { boolean change = false; synchronized (this) { if (a != null && isNewBest(score)) { best = a; this.score = score; change = true; } } if (change) pcallF(onChange); return change; } public synchronized A get() { return best; } public synchronized boolean has() { return best != null; } } public static class TextAndType { public String text; public String type; public TextAndType() { } public TextAndType(String text, String type) { this.type = type; this.text = text; } public String toString() { return "TextAndType(" + text + ", " + type + ")"; } public boolean equals(Object o) { if (!(o instanceof TextAndType)) return false; TextAndType x = (TextAndType) o; return eq(text, x.text) && eq(type, x.type); } public int hashCode() { int h = -34343004; h = h * 2 + _hashCode(text); h = h * 2 + _hashCode(type); return h; } } public static class ErrorCounter { public List> errors = new ArrayList(); public int total; public void run(Object info, Runnable r) { try { r.run(); } catch (Throwable e) { _handleException(e); errors.add(pair(info, e)); } ++total; } public void print() { if (empty(errors)) _print("No errors (tests: " + total + ")"); else _print(n2(errors, "error") + " in " + n2(total, "test") + ". Fails: " + pairsA(errors)); } } public static class MultiSet { public Map map = new HashMap(); public MultiSet(boolean useTreeMap) { if (useTreeMap) map = new TreeMap(); } public MultiSet() { } public MultiSet(Iterable c) { addAll(c); } public MultiSet(MultiSet ms) { synchronized (ms) { for (A a : ms.keySet()) add(a, ms.get(a)); } } public synchronized void add(A key) { add(key, 1); } public synchronized void addAll(Iterable c) { if (c != null) for (A a : c) add(a); } public synchronized void addAll(MultiSet ms) { for (A a : ms.keySet()) add(a, ms.get(a)); } public synchronized void add(A key, int count) { if (count <= 0) return; if (map.containsKey(key)) map.put(key, map.get(key) + count); else map.put(key, count); } public synchronized int get(A key) { Integer i = map.get(key); return i != null ? i : 0; } public synchronized boolean contains(A key) { return map.containsKey(key); } public synchronized void remove(A key) { Integer i = map.get(key); if (i != null && i > 1) map.put(key, i - 1); else map.remove(key); } public synchronized List topTen() { return getTopTen(); } public synchronized List getTopTen() { return getTopTen(10); } public synchronized List getTopTen(int maxSize) { List list = getSortedListDescending(); return list.size() > maxSize ? list.subList(0, maxSize) : list; } public synchronized List highestFirst() { return getSortedListDescending(); } public synchronized List lowestFirst() { return reversedList(getSortedListDescending()); } public synchronized List getSortedListDescending() { List list = new ArrayList(map.keySet()); Collections.sort(list, new Comparator() { public int compare(A a, A b) { return map.get(b).compareTo(map.get(a)); } }); return list; } public synchronized int getNumberOfUniqueElements() { return map.size(); } public synchronized int uniqueSize() { return map.size(); } public synchronized Set asSet() { return map.keySet(); } public synchronized NavigableSet navigableSet() { return navigableKeys((NavigableMap) map); } public synchronized Set keySet() { return map.keySet(); } public synchronized A getMostPopularEntry() { int max = 0; A a = null; for (Map.Entry entry : map.entrySet()) { if (entry.getValue() > max) { max = entry.getValue(); a = entry.getKey(); } } return a; } public synchronized void removeAll(A key) { map.remove(key); } public synchronized int size() { int size = 0; for (int i : map.values()) size += i; return size; } public synchronized MultiSet mergeWith(MultiSet set) { MultiSet result = new MultiSet(); for (A a : set.asSet()) { result.add(a, set.get(a)); } return result; } public synchronized boolean isEmpty() { return map.isEmpty(); } public synchronized String toString() { return str(map); } public synchronized void clear() { map.clear(); } public synchronized Map asMap() { return cloneMap(map); } } public static class CompilerBot { public static boolean verbose; public static File compileSnippet(String snippetID) { return compileSnippet(snippetID, ""); } public static Pair compileSnippet2(String snippetID) { return compileSnippet2(snippetID, ""); } public static File compileSnippet(String snippetID, String javaTarget) { return compileSnippet2(snippetID, javaTarget).a; } public static Pair compileSnippet2(String snippetID, String javaTarget) { String transpiledSrc = getServerTranspiled2(snippetID); int i = transpiledSrc.indexOf('\n'); String libs = transpiledSrc.substring(0, Math.max(0, i)); if (verbose) print("Compiling snippet: " + snippetID + ". Libs: " + libs); transpiledSrc = transpiledSrc.substring(i + 1); return pair(compile(transpiledSrc, libs, javaTarget, snippetID), transpiledSrc); } public static File compile(String src) { return compile(src, ""); } public static File compile(String src, String libs) { return compile(src, libs, null); } public static File compile(String src, String dehlibs, String javaTarget) { return compile(src, dehlibs, javaTarget, null); } public static File compile(String src, String dehlibs, String javaTarget, String progID) { if (verbose) print("Compiling " + l(src) + " chars"); String md5 = md5(dehlibs + "\n" + src + "\n" + progID); File jar = getJarFile(md5); if (jar == null || jar.length() <= 22) { List mainClass = findMainClass(javaTok(src)); boolean canRename = mainClass != null && useDummyMainClasses() && isSnippetID(progID) && !tok_classHasModifier(mainClass, "public"); if (verbose) print("useRenaming: " + useDummyMainClasses() + ", canRename: " + canRename + ", progID: " + progID); javaCompileToJar_optionalRename(src, dehlibs, jar, canRename ? progID : null, progID); } else { if (verbose) print("Getting classes from cache (" + jar.getAbsolutePath() + ", " + jar.length() + " bytes)"); touchFile(jar); } return jar; } public static File getJarFile(String md5) { assertTrue(isMD5(md5)); return new File(getCacheProgramDir("#1002203"), md5 + ".jar"); } } public static class T3 { public A a; public B b; public C c; public T3() { } public T3(A a, B b, C c) { this.c = c; this.b = b; this.a = a; } public T3(T3 t) { a = t.a; b = t.b; c = t.c; } public int hashCode() { return _hashCode(a) + 2 * _hashCode(b) - 4 * _hashCode(c); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof T3)) return false; T3 t = (T3) o; return eq(a, t.a) && eq(b, t.b) && eq(c, t.c); } public String toString() { return "(" + quoteBorderless(a) + ", " + quoteBorderless(b) + ", " + quoteBorderless(c) + ")"; } } public static class Pair implements Comparable> { public A a; public B b; public Pair() { } public 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); } } public static class GazelleReaction { public static String _fieldOrder = "created userID emoji"; public long created; public long userID; public String emoji; public GazelleReaction() { } public GazelleReaction(long created, long userID, String emoji) { this.emoji = emoji; this.userID = userID; this.created = created; } public String toString() { return "GazelleReaction(" + created + ", " + userID + ", " + emoji + ")"; } public boolean equals(Object o) { if (!(o instanceof GazelleReaction)) return false; GazelleReaction x = (GazelleReaction) o; return eq(created, x.created) && eq(userID, x.userID) && eq(emoji, x.emoji); } public int hashCode() { int h = 1661428073; h = h * 2 + _hashCode(created); h = h * 2 + _hashCode(userID); h = h * 2 + _hashCode(emoji); return h; } } public static class GazelleLine { public static String _fieldOrder = "timestamp text msgID reactions user bot extras"; public long timestamp; public String text; public long msgID; public List reactions; public GazelleLine() { } public GazelleLine(long timestamp, String text, long msgID, List reactions) { this.reactions = reactions; this.msgID = msgID; this.text = text; this.timestamp = timestamp; } public String toString() { return "GazelleLine(" + timestamp + ", " + text + ", " + msgID + ", " + reactions + ")"; } public boolean equals(Object o) { if (!(o instanceof GazelleLine)) return false; GazelleLine x = (GazelleLine) o; return eq(timestamp, x.timestamp) && eq(text, x.text) && eq(msgID, x.msgID) && eq(reactions, x.reactions); } public int hashCode() { int h = -1898653900; h = h * 2 + _hashCode(timestamp); h = h * 2 + _hashCode(text); h = h * 2 + _hashCode(msgID); h = h * 2 + _hashCode(reactions); return h; } public String user; public boolean bot; public Map extras; } public static class RuleEngine2_MatchedRule { public String globalID = aGlobalID(); public RuleEngine2.Rule rule; public int iCond; public Map map; public Map mappingQuality = new HashMap(); public List, List>> matchedLines = new ArrayList(); public String tokenizationFunction; public String outTokenizer; public List remainingConditions; public List remainingConditionsWithType; public Integer qualitySum; public Integer nPossibleVars; public String out; public Map inputsByType; public int qualitySum() { if (qualitySum == null) qualitySum = intSum(values(mappingQuality)) - l(map); return qualitySum; } public int nPossibleVars() { if (nPossibleVars == null) nPossibleVars = l(possibleVars()); return nPossibleVars; } public boolean isSpecialRule() { return rule instanceof RuleEngine2.SimplifyWithRule; } public double relativeQuality() { return isSpecialRule() ? 0 : doubleRatio(qualitySum(), nPossibleVars()); } public Set possibleVars() { return asCISet(codeTokens(tokenize(first(rule.in)))); } public RuleEngine2.Rule applyMapping() { RuleEngine2.Rule r = new RuleEngine2.Rule(); r.in = map(rule.in, new F1() { public String get(String x) { try { return applyMappingTo(x); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "applyMappingTo(x)"; } }); r.out = applyMappingTo(rule.out); return r; } public String appliedRuleText() { return applyMapping().asText(); } public String outText() { if (out == null) out = join(ai_mapCodeTokensWithMap(outTokenize(rule.out), map)); return out; } public String applyMappingTo(String s) { return s == null ? null : join(ai_mapCodeTokensWithMap(tokenize(s), map)); } public List tokenize(String s) { return (List) callAndMake(assertNotNull(tokenizationFunction), s); } public List outTokenize(String s) { return (List) callAndMake(assertNotNull(or(outTokenizer, tokenizationFunction)), s); } public boolean moreConditions() { return rule != null && iCond < l(rule.in); } public String ruleID() { return rule.globalID; } public void flush() { if (tokenizationFunction != null || outTokenizer != null) out = null; } public String toString() { return "MatchedRule " + ruleID() + " with " + map + (moreConditions() ? " [unsatisfied]" : ""); } } public static class JavaXClassLoader extends URLClassLoader { public String progID; public List files; public Set triedToLoad = synchroSet(); public Set loadedClasses = synchroSet(); public boolean retired; public Object retiredMarker; public JavaXClassLoader(String progID, List files) { this(progID, files, getSystemClassLoader()); } public JavaXClassLoader(String progID, List files, ClassLoader parent) { super(new URL[0], parent); this.progID = progID; this.files = files; { try { for (File f : files) addURL(f.toURI().toURL()); } catch (Exception __e) { throw rethrow(__e); } } fixACCInClassLoader(this); } public Class findClass(String name) throws ClassNotFoundException { boolean triedBefore = !triedToLoad.add(name); try { Class c = super.findClass(name); loadedClasses.add(c); if (eq(name, "main")) callOpt(javax(), "registerAMainClass", c); return c; } catch (ClassNotFoundException e) { throw new ClassNotFoundException("Class " + name + " not found in " + joinWithComma(map("f2s", files)) + " (progID=" + progID + ")" + (triedBefore ? ", tried to load before" : ""), e); } } public String toString() { return "JavaXClassLoader[" + systemHashCodeHex(this) + "] - " + progID; } } public static class JavaXClassLoaderWithParent extends JavaXClassLoader { public ClassLoader virtualParent; public JavaXClassLoaderWithParent(String progID, List files, ClassLoader virtualParent) { super(progID, files); this.virtualParent = virtualParent; } public Class findClass(String name) throws ClassNotFoundException { if (virtualParent != null && !eq(name, "main") && !name.startsWith("main$")) { try { return virtualParent.loadClass(name); } catch (ClassNotFoundException e) { } } return super.findClass(name); } } public abstract static class F0 { public abstract A get(); } public abstract static class F1 { public abstract B get(A a); } public abstract static class IterableIterator implements Iterator, Iterable { public Iterator iterator() { return this; } public void remove() { unsupportedOperation(); } } public abstract static class F2 { public abstract C get(A a, B b); } public static class Flag { public boolean up; public synchronized boolean raise() { if (!up) { up = true; notifyAll(); return true; } else return false; } public synchronized void waitUntilUp() { while (!up) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void waitUntilUp(long timeout) { if (!up) { try { wait(timeout); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized boolean isUp() { return up; } public boolean get() { return isUp(); } public String toString() { return isUp() ? "up" : "down"; } public void waitForThisOr(Flag otherFlag) { try { while (!isUp() && !otherFlag.isUp()) Thread.sleep(50); } catch (Exception __e) { throw rethrow(__e); } } } public static class BetterLabel extends JLabel { public boolean autoToolTip = true; public BetterLabel() { final WeakReference me = new WeakReference(this); componentPopupMenu(this, BetterLabel_menuItems(me)); } public BetterLabel(String text) { this(); this.setText(text); } public void setText(String text) { super.setText(text); if (autoToolTip) if (!swic(text, "")) setToolTipText(nullIfEmpty(text)); } } public static VF1 BetterLabel_menuItems(final WeakReference me) { return new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try { copyTextToClipboard(me.get().getText()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(me.get().getText());"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n copyTextToClipboard(me..."; } }; } public static class MRUCache extends LinkedHashMap { public int maxSize = 10; public MRUCache() { } public MRUCache(int maxSize) { this.maxSize = maxSize; } public boolean removeEldestEntry(Map.Entry eldest) { return size() > maxSize; } } public abstract static class CloseableIterableIterator extends IterableIterator implements AutoCloseable { public void close() throws Exception { } } public static class ExpiringMap2 extends AbstractMap { public Map> byKey = new HashMap(); public PriorityBlockingQueue> queue = new PriorityBlockingQueue(); public long standardExpiryTime; public boolean renewOnOverwrite = true, renewOnGet; public Object onChange; public ExpiringMap2() { } public ExpiringMap2(long standardExpiryTime) { this.standardExpiryTime = standardExpiryTime; } public ExpiringMap2(long standardExpiryTime, Object onChange) { this.onChange = onChange; this.standardExpiryTime = standardExpiryTime; } public synchronized boolean clean() { boolean changes = false; Pair p; while ((p = queue.peek()) != null && sysTime() >= p.a) { p = queue.poll(); Pair v = byKey.get(p.b); if (v != null) { byKey.remove(p.b); changes = true; change(); } } return changes; } public void change() { callF(onChange); } public synchronized B put(A a, B b) { clean(); long timeout = sysTime() + standardExpiryTime; Pair p = byKey.get(a); if (p != null && renewOnOverwrite) queue.remove(new Pair(p.a, a)); byKey.put(a, pair(timeout, b)); change(); if (p == null || renewOnOverwrite) queue.add(new Pair(timeout, a)); return pairB(p); } public synchronized B remove(Object a) { clean(); Pair p = byKey.get(a); if (p == null) return null; queue.remove(new Pair(p.a, a)); byKey.remove(a); change(); return p.b; } public synchronized B get(Object a) { clean(); Pair p = byKey.get(a); if (renewOnGet && p != null) { queue.remove(new Pair(p.a, a)); long timeout = sysTime() + standardExpiryTime; byKey.put((A) a, pair(timeout, p.b)); queue.add(new Pair(timeout, a)); } return pairB(p); } public synchronized Set> entrySet() { clean(); return synchronizedSet(mapValues("pairB", byKey).entrySet()); } public synchronized Set keySet() { clean(); return synchronizedSet(byKey.keySet()); } public synchronized int size() { clean(); return byKey.size(); } public void setStandardExpiryTime(long ms) { standardExpiryTime = ms; } public synchronized ExpiringMap2 setMap(Map innerMap) { byKey = innerMap; return this; } } public static class JavaXClassLoaderWithParent2 extends JavaXClassLoader { public ClassLoader virtualParent; public List classesToSkip; public JavaXClassLoaderWithParent2(String progID, List files, ClassLoader virtualParent, List classesToSkip) { super(progID, files); this.virtualParent = virtualParent; this.classesToSkip = classesToSkip; } public Class findClass(String name) throws ClassNotFoundException { if (shouldDelegate(name)) { Class c = virtualParent.loadClass(name); if (c != null) return c; } return super.findClass(name); } public boolean shouldDelegate(String name) { for (String s : classesToSkip) if (eq(name, s) || startsWith(name, s + "$")) return true; return false; } } public static class PosNegScore { public static String _fieldOrder = "pos neg"; public double pos; public double neg; public PosNegScore() { } public PosNegScore(double pos, double neg) { this.neg = neg; this.pos = pos; } public String toString() { return "PosNegScore(" + pos + ", " + neg + ")"; } public boolean equals(Object o) { if (!(o instanceof PosNegScore)) return false; PosNegScore x = (PosNegScore) o; return eq(pos, x.pos) && eq(neg, x.neg); } public int hashCode() { int h = 1208109366; h = h * 2 + _hashCode(pos); h = h * 2 + _hashCode(neg); return h; } } public static interface Producer { public A next(); } public static ThreadLocal DynamicObject_loading = new ThreadLocal(); public static class DynamicObject { public String className; public LinkedHashMap fieldValues = new LinkedHashMap(); public DynamicObject() { } public DynamicObject(String className) { this.className = className; } } public static interface IF1 { public B get(A a); } public static class PersistableThrowable { public String className; public String msg; public String stacktrace; public PersistableThrowable() { } public 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; } } public static class GazelleFulfillment { public String line; public String rule; public String varMap; public String judgement; public String matchedRuleStruct; public String context; public Map varMap() { return safeUnstructureMap(varMap); } public static String _fieldOrder = "line rule varMap judgement matchedRuleStruct context"; public String toString() { return sfu(varMap); } } public static interface IVar { public void set(A a); public A get(); public boolean has(); public void clear(); } public static class MechMode { public Object readMode; public Object writeMode; public MechMode() { } public MechMode(Object readMode, Object writeMode) { this.writeMode = writeMode; this.readMode = readMode; } public String toString() { return "MechMode(" + readMode + ", " + writeMode + ")"; } public boolean equals(Object o) { if (!(o instanceof MechMode)) return false; MechMode x = (MechMode) o; return eq(readMode, x.readMode) && eq(writeMode, x.writeMode); } public int hashCode() { int h = -866263200; h = h * 2 + _hashCode(readMode); h = h * 2 + _hashCode(writeMode); return h; } } public static B pairB(Pair p) { return p == null ? null : p.b; } public static Field makeAccessible(Field f) { f.setAccessible(true); return f; } public static Method makeAccessible(Method m) { m.setAccessible(true); return m; } public static Set allInterfacesImplementedBy(Class c) { if (c == null) return null; HashSet set = new HashSet(); allInterfacesImplementedBy_find(c, set); return set; } public 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); } public 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; } public 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; } public static void gazelle_addSharedClasses() { hotwire_addSharedClasses(RuleEngine2.class, GazelleTree.class, GazelleEvalContext.class); } public static String fsi(String id) { return formatSnippetID(id); } public static List quoteAll(Collection l) { List x = new ArrayList(); for (String s : l) x.add(quote(s)); return x; } public static String appendSquareBracketed(String b) { return empty(b) ? "" : "" + " [" + b + "]"; } public static String appendSquareBracketed(String a, String b) { return empty(b) ? a : a + appendSquareBracketed(b); } public static List listPlusNempties(Collection l, String... more) { return concatLists_conservative(l, nempties(asList(more))); } public static void addIfNempty(Collection l, String s) { if (nempty(s)) l.add(s); } public static void addIfNempty(Collection l, Map m) { if (nempty(m)) l.add(m); } public static void addIfNempty(Collection l, Collection c) { if (nempty(c)) l.add(c); } public static String formatDouble(double d, int digits) { String format = digits <= 0 ? "0" : "0." + rep(digits, '#'); return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)).format(d); } public static List reversed(Collection l) { return reversedList(l); } public static List reversed(A[] l) { return reversedList(asList(l)); } public static String reversed(String s) { return reversedString(s); } public static void _add(BitSet bs, int i) { add(bs, i); } public static boolean _add(Collection c, A a) { return add(c, a); } public static void _add(Container c, Component x) { add(c, x); } public static Map putAll(Map a, Map b) { if (a != null) a.putAll(b); return a; } public static Set keySet(Map map) { return map == null ? new HashSet() : map.keySet(); } public static Set keySet(Object map) { return keys((Map) map); } public static Set keySet(MultiSet ms) { return ms.keySet(); } public static Set keySet(MultiMap mm) { return mm.keySet(); } public static A reverseGet(List l, int idx) { if (l == null || idx < 0) return null; int n = l(l); return idx < n ? l.get(n - 1 - idx) : null; } public static void gazelle_parseInstruction(RuleEngine2.SimplifyWithRule r) { Matches m = new Matches(); String s = r.text; if (match("simplify with *", s, m)) { r._function = m.unq(0); return; } else if (match("simplify with * on tree", s, m)) { r.callOnTree = true; { r._function = m.unq(0); return; } } else if (match("drop after word *", s, m)) { final String word = m.unq(0); { r._function = new F1() { public Object get(String s) { try { return tok_dropStartingWithWord(word, s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tok_dropStartingWithWord(word, s)"; } }; return; } } else if (match("group words *", s, m)) { final String words = m.unq(0); { r._function = new F1() { public Object get(String s) { try { return tok_groupPhrase(s, words); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tok_groupPhrase(s, words)"; } }; return; } } else if (match("split with *", s, m)) { r.isSplitRule = true; { r._function = m.unq(0); return; } } } public static List addToOrCreateList(List l, A a) { return addDyn(l, a); } public static List listSetWithCreate(List l, int i, A a) { if (l == null) l = new ArrayList(); listSet(l, i, a); return l; } public static String gazelle_purposeFromComments(List comments) { Matches m = new Matches(); for (String s : unnull(comments)) { if (swic_trim(s, "purpose:", m)) return m.rest(); } return null; } public static String gazelle_purposeFromComments(String comments) { return gazelle_purposeFromComments(tlft(comments)); } public static Pair ai_rule_pair_expandPlusArrow(Pair rule) { if (endsWith(pairA(rule), "+")) return pair(rule.a + " " + rule.b, rule.b); return rule; } public static List tok_splitAtPlusAtBeginningOfLine(String s) { List indices = new ArrayList(); List tok = javaTokWithAllBrackets(s); for (int i = 1; i < l(tok); i += 2) if (eqGet(tok, i, "+") && containsNewLine(get(tok, i - 1))) indices.add(i); return splitAtTokenIndices(tok, indices); } public static boolean jMatchStart(String pat, String s) { return jMatchStart(pat, s, null); } public static boolean jMatchStart(String pat, String s, Matches matches) { if (s == null) return false; return jMatchStart(pat, javaTok(s), matches); } public static boolean jMatchStart(String pat, List toks, Matches matches) { List tokpat = jfind_preprocess(javaTok(pat)); if (toks.size() < tokpat.size()) return false; String[] m = match2x(tokpat, toks.subList(0, tokpat.size())); if (m == null) return false; if (matches != null) { matches.m = new String[m.length + 1]; arraycopy(m, matches.m); matches.m[m.length] = join(toks.subList(tokpat.size(), toks.size())); } return true; } public static A nextToLast(List l) { return get(l, l(l) - 2); } public static List tok_groupLastTokensToMatchPattern(List tok, List tokPat) { return concatLists(subList(tok, 0, l(tokPat) - 2), ll(curly(joinSubList(tok, l(tokPat) - 2, l(tok) - 1)), last(tok))); } public static Set ai_wordsInBothSidesOfPair_uncurly(Pair p) { return mapCISet("uncurly", ai_wordsInBothSidesOfPair(p)); } public static A firstWhere(Collection c, Object... data) { return findWhere(c, data); } public static int _hashCode(Object a) { return a == null ? 0 : a.hashCode(); } public static A _print(A a) { return print(a); } public static void _print() { print(); } public static List pairsA(Collection> l) { return firstOfPairs(l); } public static NavigableSet navigableKeys(NavigableMap map) { return map == null ? new TreeSet() : map.navigableKeySet(); } public static NavigableSet navigableKeys(MultiSet ms) { return ((NavigableMap) ms.map).navigableKeySet(); } public static NavigableSet navigableKeys(MultiMap mm) { return ((NavigableMap) mm.data).navigableKeySet(); } public static boolean getServerTranspiled2_allowLocalFallback = true, getServerTranspiled2_localFallbackVerbose = true; public static String getServerTranspiled2(String id) { String transpiled = loadCachedTranspilation(id); String md5 = null; if (machineIsOffline() || isOfflineMode() || isLocalSnippet(id)) return transpiled; if (transpiled != null) md5 = md5(transpiled); String transpiledSrc; try { transpiledSrc = getServerTranspiled(formatSnippetID(id), md5); } catch (Throwable e) { if (!getServerTranspiled2_allowLocalFallback) rethrow(e); printExceptionShort(e); if (getServerTranspiled2_localFallbackVerbose) print("Fallback to local code"); return transpiled; } if (eq(transpiledSrc, "SAME")) { if (!isTrue(loadPage_silent.get())) print("SAME"); return transpiled; } return transpiledSrc; } public static List findMainClass(List tok) { for (List c : reversedList(allClasses(tok))) { String name = getClassDeclarationName(c); if (eq(name, "main") || name.startsWith("x")) return c; } return findBlock("m {", tok); } public static boolean useDummyMainClasses() { return true; } public static boolean tok_classHasModifier(List classDecl, String modifier) { if (classDecl == null) return false; int i = classDecl.indexOf("class"); return subList(classDecl, 0, i).contains(modifier); } public static boolean javaCompileToJar_useRAMDisk; public static File javaCompileToJar_optionalRename(String src, File destJar, String progIDForRename) { return javaCompileToJar_optionalRename(src, "", destJar, progIDForRename); } public static synchronized File javaCompileToJar_optionalRename(String src, String dehlibs, File destJar, String progIDForRename) { return javaCompileToJar_optionalRename(src, dehlibs, destJar, progIDForRename, null); } public static synchronized File javaCompileToJar_optionalRename(String src, String dehlibs, File destJar, String progIDForRename, String progID) { String javaTarget = null; String dummyClass = "main"; if (progIDForRename != null) { dummyClass = dummyMainClassName(progIDForRename); src += "\nclass " + dummyClass + "{}"; } String md5 = md5(src); File jar = destJar; Class j = getJavaX(); if (javaTarget != null) setOpt(j, "javaTarget", javaTarget); File srcDir = tempDir(); String className = "main"; String fileName = dummyClass + ".java"; List tok = javaTok(src); String packageName = tok_packageName(tok); if (packageName != null) fileName = packageName.replace(".", "/") + "/" + tok_firstClassName(tok) + ".java"; File mainJava = new File(srcDir, fileName); saveTextFile(mainJava, src); File classesDir = javaCompileToJar_useRAMDisk ? tempDirPossiblyInRAMDisk() : tempDir(); try { List libraries = new ArrayList(); Matcher m = Pattern.compile("\\d+").matcher(dehlibs); while (m.find()) { String libID = m.group(); assertTrue(isSnippetID(libID)); libraries.add(loadLibraryOrSrcLib(libID)); } libraries.add(pathToJavaxJar()); String compilerOutput; try { compilerOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir); } catch (Throwable e) { compilerOutput = (String) get(getJavaX(), "javaCompilerOutput"); String msg = cleanJavaCompilerOutput(compilerOutput); if (neqic(e.getMessage(), "Java compiler returned errors.") || empty(msg)) msg = appendWithNewLine(msg, str(e)); throw fail(msg); } compilerOutput = cleanJavaCompilerOutput("Annotation processing got disabled, since it requires a 1.6 compliant JVM"); if (nempty(compilerOutput)) { print("Compiler said: " + compilerOutput); } if (!anyFileWithExtensionInDir(classesDir, ".class")) throw fail("No classes generated"); saveTextFile(new File(classesDir, "main.java"), src); if (nempty(dehlibs)) saveTextFile(new File(classesDir, "libraries"), dehlibs); saveTextFile(new File(classesDir, "progID"), progID); dir2zip_recurse_verbose = false; int n = dir2zip_recurse(classesDir, jar); return jar; } finally { if (isInRAMDisk(classesDir)) deleteDirectory(classesDir); } } public static void touchFile(File file) { try { closeRandomAccessFile(newRandomAccessFile(mkdirsForFile(file), "rw")); } catch (Exception __e) { throw rethrow(__e); } } public static File getCacheProgramDir() { return getCacheProgramDir(getProgramID()); } public static File getCacheProgramDir(String snippetID) { return new File(userHome(), "JavaX-Caches/" + formatSnippetIDOpt(snippetID)); } public static String quoteBorderless(Object o) { if (o == null) return "null"; return quoteBorderless(str(o)); } public static String quoteBorderless(String s) { if (s == null) return "null"; StringBuilder out = new StringBuilder((int) (l(s) * 1.5)); quoteBorderless_impl(s, out); return out.toString(); } public static void quoteBorderless_impl(String s, StringBuilder out) { 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 out.append(c); } } public static int hashCodeFor(Object a) { return a == null ? 0 : a.hashCode(); } public static int intSum(Collection c, String field) { int sum = 0; for (Object o : unnull(c)) sum += toInt(getOpt(o, field)); return sum; } public static int intSum(Iterable l) { int sum = 0; for (Integer i : unnull(l)) if (i != null) sum += i; return sum; } public static double doubleRatio(double x, double y) { return y == 0 ? 0 : x / y; } public static List ai_mapCodeTokensWithMap(List tok, final Map map) { return mapCodeTokens(tok, new F1() { public String get(String s) { try { return getOrKeep_tryUncurlied(map, s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getOrKeep_tryUncurlied(map, s)"; } }); } public static void fixACCInClassLoader(Object o) { try { AccessControlContext acc = vm_globalACC(); if (acc != null) replaceACCInClassLoader(o, acc); } catch (Throwable __e) { _handleException(__e); } } public static String systemHashCodeHex(Object o) { return intToHex(identityHashCode(o)); } public static Iterator iterator(Iterable c) { return c == null ? emptyIterator() : c.iterator(); } public static UnsupportedOperationException unsupportedOperation() { throw new UnsupportedOperationException(); } public static ThreadLocal componentPopupMenu_mouseEvent; public static void componentPopupMenu_init() { { swing(new Runnable() { public void run() { try { if (componentPopupMenu_mouseEvent == null) componentPopupMenu_mouseEvent = (ThreadLocal) vm_generalMap_get("mouseEvent"); if (componentPopupMenu_mouseEvent == null) vm_generalMap_put("componentPopupMenu_mouseEvent", componentPopupMenu_mouseEvent = new ThreadLocal()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (componentPopupMenu_mouseEvent == null)\r\n componentPopupMenu_mouseEve..."; } }); } } public static void componentPopupMenu(final JComponent component, final Object menuMaker) { if (component != null && menuMaker != null) { swing(new Runnable() { public void run() { try { Object adapter = componentPopupMenu_initForComponent(component); ((List) get(adapter, "maker")).add(menuMaker); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object adapter = componentPopupMenu_initForComponent(component);\r\n ((List)..."; } }); } } public static Object componentPopupMenu_initForComponent(final JComponent component) { return component == null ? null : swing(new F0() { public Object get() { try { componentPopupMenu_init(); Object adapter = findComponentPopupMenuListener_gen(component); if (adapter == null) { componentPopupMenu_Adapter a = new componentPopupMenu_Adapter(); component.addMouseListener(a); adapter = a; } return adapter; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "componentPopupMenu_init();\r\n O adapter = findComponentPopupMenuListener_ge..."; } }); } public static class componentPopupMenu_Adapter extends MouseAdapter { public List maker = new ArrayList(); public void mousePressed(MouseEvent e) { displayMenu(e); } public void mouseReleased(MouseEvent e) { displayMenu(e); } public void displayMenu(MouseEvent e) { if (e.getSource() instanceof JInternalFrame) return; if (e.isPopupTrigger()) displayMenu2(e); } public void displayMenu2(MouseEvent e) { JPopupMenu menu = new JPopupMenu(); int emptyCount = menu.getComponentCount(); AutoCloseable __1489 = tempSetTL(componentPopupMenu_mouseEvent, e); try { for (Object menuMaker : maker) pcallF(menuMaker, menu); vmBus_send("showingPopupMenu", e.getComponent(), menu); if (menu.getComponentCount() != emptyCount) menu.show(e.getComponent(), e.getX(), e.getY()); } finally { _close(__1489); } } } public static A setToolTipText(final A c, final Object toolTip) { if (c == null) return null; { swing(new Runnable() { public void run() { try { String s = nullIfEmpty(str(toolTip)); if (neq(s, c.getToolTipText())) c.setToolTipText(s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = nullIfEmpty(str(toolTip));\r\n if (neq(s, c.getToolTipText()))\r\n ..."; } }); } return c; } public static A setToolTipText(Object toolTip, A c) { return setToolTipText(c, toolTip); } public static void addMenuItem(JPopupMenu menu, String text, Object action) { menu.add(jmenuItem(text, action)); } public static void addMenuItem(JPopupMenu menu, JMenuItem menuItem) { menu.add(menuItem); } public static void addMenuItem(JMenu menu, String text, Object action) { menu.add(jmenuItem(text, action)); } public static void addMenuItem(Menu menu, String text, Object action) { menu.add(menuItem(text, action)); } public static void addMenuItem(JMenu menu, JMenuItem menuItem) { menu.add(menuItem); } public static String copyTextToClipboard(Object _text) { String text = str(_text); StringSelection selection = new StringSelection(text); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection); vmBus_send("newClipboardContents", text); return text; } public static long sysTime() { return sysNow(); } public static void change() { callOpt(getOptMC("mainConcepts"), "allChanged"); } public static void hotwire_addSharedClasses(Collection classes) { addAll(hotwire_classesToShare, map("className", classes)); } public static void hotwire_addSharedClasses(Class... classes) { hotwire_addSharedClasses(asList(classes)); } public static List concatLists_conservative(List a, List b) { if (empty(a)) return b; if (empty(b)) return a; return concatLists(a, b); } public static List concatLists_conservative(Collection a, Collection b) { if (empty(a) && b instanceof List) return ((List) b); if (empty(b) && a instanceof List) return ((List) a); return concatLists(a, b); } public static List nempties(Collection c) { return filterNempty(c); } public static String rep(int n, char c) { return repeat(c, n); } public static String rep(char c, int n) { return repeat(c, n); } public static List rep(A a, int n) { return repeat(a, n); } public static List rep(int n, A a) { return repeat(n, a); } public static String reversedString(String s) { return reverseString(s); } public static String tok_dropStartingWithWord(String word, String s) { List tok = javaTokWithBrackets(s); int i = indexOfIC(tok, word); return i < 0 ? s : joinSubList(tok, 0, i - 1); } public static List tok_groupPhrase(List tok, String phrase) { List tokPhrase = dropFirstAndLast(javaTok_cached(phrase)); List l = indicesOfSubListIC(tok, tokPhrase); for (int i : l) { int j = i + l(tokPhrase) - 1; if (i == 1 && j == l(tok) - 2) continue; String pre = get(tok, i - 1), post = get(tok, j + 1); if (endsWith(pre, "{") && startsWith(post, "}")) continue; tokPrepend(tok, i, "{"); tokAppend(tok, j, "}"); } return tok; } public static String tok_groupPhrase(String s, String phrase) { return join(tok_groupPhrase(javaTok(s), phrase)); } public static List addDyn(List l, A a) { if (l == null) l = new ArrayList(); l.add(a); return l; } public static void listSet(List l, int i, A a, A emptyElement) { if (i < 0) return; while (i >= l(l)) l.add(emptyElement); l.set(i, a); } public static void listSet(List l, int i, A a) { listSet(l, i, a, null); } public static boolean swic_trim(String a, String b, Matches m) { if (!swic(a, b)) return false; m.m = new String[] { trim(substring(a, l(b))) }; return true; } public static List javaTokWithAllBrackets(String s) { return javaTokPlusBrackets2(s); } public static boolean eqGet(List l, int i, Object o) { return eq(get(l, i), o); } public static boolean eqGet(Map map, A key, Object o) { return eq(mapGet(map, key), o); } public static List splitAtTokenIndices(List tok, List indices) { List l = new ArrayList(); for (int iI = -1; iI < l(indices); iI++) { int i = or(get(indices, iI), 0) + 1; int j = or(get(indices, iI + 1), l(tok)); l.add(trimJoin(tok.subList(i, j))); } return l; } public static String[] match2x(List pat, List tok) { ArrayList result = new ArrayList(); if (pat.size() != tok.size()) return null; for (int i = 1; i < pat.size(); i += 2) { String p = pat.get(i), t = tok.get(i); boolean match; if (eq(p, "*")) match = true; else if (eq(p, "")) match = isQuoted(t); else if (eq(p, "")) match = isIdentifier(t); else if (eq(p, "")) match = isInteger(t); else { if (!eq(p, t)) return null; continue; } if (!match) return null; result.add(t); } return result.toArray(new String[result.size()]); } public static TreeSet mapCISet(Object f, Iterable l) { return mapToCISet(f, l); } public static Set ai_wordsInBothSidesOfPair(Pair p) { return filterCISet("hasLetterOrDigit", ciSetIntersection(javaTokWithBracketsPlusJavaTokC(p.a), javaTokWithBracketsPlusJavaTokC(p.b))); } public static List firstOfPairs(Collection> l) { List out = new ArrayList(); for (Pair p : unnull(l)) out.add(firstOfPair(p)); return out; } public static boolean machineIsOffline() { return isFalse(callF(vmGeneralMap_get("areWeOnline"))); } public static boolean isOfflineMode() { return eq("1", trim(loadProgramTextFile("#1005806", "offline-mode"))); } public static boolean isLocalSnippet(String snippetID) { return isLocalSnippetID(snippetID); } public static boolean isLocalSnippet(long snippetID) { return isLocalSnippetID(snippetID); } public static String getServerTranspiled(String snippetID) { return getServerTranspiled(snippetID, null); } public static String getServerTranspiled(String snippetID, String expectedMD5) { try { long id = parseSnippetID(snippetID); String text = loadPage_utf8(tb_mainServer() + "/tb-int/get-transpiled.php?raw=1&withlibs=1&id=" + id + "&utf8=1" + (l(expectedMD5) > 1 ? "&md5=" + urlencode(expectedMD5) : "") + standardCredentials()); if (nempty(text) && neq(text, "SAME")) saveTranspiledCode(snippetID, text); return text; } catch (Exception __e) { throw rethrow(__e); } } public static void printExceptionShort(Throwable e) { print(exceptionToStringShort(e)); } public static HashSet allClasses_keywords = lithashset("class", "interface", "enum", "sclass", "sinterface", "record", "srecord"); public static List> allClasses(List tok) { List> l = new ArrayList(); int n = tok.size(); HashSet _allClasses_keywords = allClasses_keywords; for (int i = 1; i < n; i += 2) { String t = tok.get(i); if ("{".equals(t)) i = findEndOfBlock(tok, i) - 1; else if (_allClasses_keywords.contains(t) && (i == 1 || !eqGetOneOf(tok, i - 2, ".", "include"))) { int j = i; while (j < n && !tok.get(j).equals("{")) j += 2; j = findEndOfBlock(tok, j) + 1; i = leftScanModifiers(tok, i); l.add(tok.subList(i - 1, Math.min(n, j))); i = j - 2; } } return l; } public static List> allClasses(String text) { return allClasses(javaTok(text)); } public static String getClassDeclarationName(List tok) { if (tok != null) for (int i = 1; i + 2 < tok.size(); i += 2) if (allClasses_keywords.contains(tok.get(i)) && isIdentifier(tok.get(i + 2))) return tok.get(i + 2); return null; } public static List findBlock(String pat, List tok) { List tokpat = javaTok(pat); int i = findCodeTokens(tok, toStringArray(codeTokensOnly(tokpat))); if (i < 0) return null; int bracketIdx = i + tokpat.size() - 3; assertEquals("{", tok.get(bracketIdx)); int endIdx = findEndOfBlock(tok, bracketIdx); return subList(tok, i - 1, endIdx + 1); } public static String dummyMainClassName(String progID) { return "m" + psI(progID); } public static File tempDir() { return makeTempDir(); } public static String tok_packageName(List tok) { int i = jfind(tok, "package"); if (i < 0) return ""; i += 2; int j = jfind(tok, i, ";"); if (j < 0) return ""; return join(codeTokensOnly(subList(tok, i - 1, j))); } public static String tok_firstClassName(List tok) { int i = jfind(tok, "class "); return i < 0 ? null : tok.get(i + 2); } public static File tempDirPossiblyInRAMDisk() { File f = linux_fileInRamDisk(aGlobalID()); if (f != null) { f.mkdirs(); return f; } return makeTempDir(); } public static boolean loadLibraryOrSrcLib_srcLibsEnabled = true; public static File loadLibraryOrSrcLib(String snippetID) { try { long id = parseSnippetID(snippetID); boolean srcLib = loadLibraryOrSrcLib_srcLibsEnabled && isMarkedAsSrcLib(snippetID); if (srcLib) return pairA(hotwire_compile(snippetID)); File f = DiskSnippetCache_getLibrary(id); if (fileSize(f) != 0) return f; try { return loadDataSnippetToFile(snippetID); } catch (Throwable e) { if (loadLibraryOrSrcLib_srcLibsEnabled && nempty(loadSnippet(snippetID))) { markAsSrcLib(snippetID); return pairA(hotwire_compile(snippetID)); } throw rethrow(e); } } catch (Exception __e) { throw rethrow(__e); } } public static File pathToJavaxJar() { try { int x = latestInstalledJavaX(); File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar"); if (!xfile.isFile()) { print("Saving " + f2s(xfile)); String url = "http://tinybrain.de/x30.jar"; byte[] data = loadBinaryPage(url); if (data.length < 1000000) throw fail("Could not load " + url); saveBinaryFile(xfile.getPath(), data); } return xfile; } catch (Exception __e) { throw rethrow(__e); } } public static String cleanJavaCompilerOutput(String s) { return dropPrefixTrim("Annotation processing got disabled, since it requires a 1.6 compliant JVM", s); } public static String appendWithNewLine(String a, String b) { if (empty(b)) return a; if (empty(a)) return b; return addSuffix(a, "\n") + b; } public static boolean anyFileWithExtensionInDir(File dir, String ext) { return nempty(filesWithExtension(ext, findAllFiles_noDirs(dir))); } public static boolean dir2zip_recurse_verbose; public static int dir2zip_recurse(File inDir, File zip) { return dir2zip_recurse(inDir, zip, ""); } public static int dir2zip_recurse(File inDir, File zip, String outPrefix) { try { mkdirsForFile(zip); FileOutputStream fout = newFileOutputStream(zip); ZipOutputStream outZip = new ZipOutputStream(fout); try { return dir2zip_recurse(inDir, outZip, outPrefix, 0); } finally { outZip.close(); } } catch (Exception __e) { throw rethrow(__e); } } public static int dir2zip_recurse(File inDir, ZipOutputStream outZip) { return dir2zip_recurse(inDir, outZip, "", 0); } public static int dir2zip_recurse(File inDir, ZipOutputStream outZip, String outPrefix, int level) { try { if (++level >= 20) throw fail("woot? 20 levels in zip?"); List files = new ArrayList(); for (File f : listFiles(inDir)) files.add(f); int n = 0; sortFilesByName(files); for (File f : files) { if (f.isDirectory()) { print("dir2zip_recurse: Scanning " + f.getAbsolutePath()); n += dir2zip_recurse(f, outZip, outPrefix + f.getName() + "/", level); } else { if (dir2zip_recurse_verbose) print("Copying " + f.getName()); outZip.putNextEntry(new ZipEntry(outPrefix + f.getName())); InputStream fin = new FileInputStream(f); copyStream(fin, outZip); fin.close(); ++n; } } return n; } catch (Exception __e) { throw rethrow(__e); } } public static boolean isInRAMDisk(File f) { return startsWith(f2s(f), "/dev/shm"); } public static void deleteDirectory(File dir) { deleteDirectory(dir, false, false); } public static void deleteDirectory(File dir, boolean verbose, boolean testRun) { deleteAllFilesInDirectory(dir, verbose, testRun); if (verbose) print((testRun ? "Would delete " : "Deleting ") + dir.getAbsolutePath()); if (!testRun) dir.delete(); } public static void closeRandomAccessFile(RandomAccessFile f) { if (f != null) try { f.close(); callJavaX("dropIO", f); } catch (Throwable e) { printStackTrace(e); } } public static RandomAccessFile newRandomAccessFile(File path, String mode) throws IOException { boolean forWrite = mode.indexOf('w') >= 0; if (forWrite) mkdirsForFile(path); RandomAccessFile f = new RandomAccessFile(path, mode); callJavaX("registerIO", f, path, forWrite); return f; } public static List mapCodeTokens(Object f, List l) { List out = new ArrayList(); for (int i = 0; i < l(l); i++) { Object o = l.get(i); out.add(odd(i) ? callF(f, o) : o); } return out; } public static List mapCodeTokens(List l, Object f) { return mapCodeTokens(f, l); } public static String getOrKeep_tryUncurlied(Map map, String a) { String v = map.get(a); if (v != null) return v; String b = uncurly(a); if (a != b && (v = map.get(b)) != null) return v; return a; } public static AccessControlContext vm_globalACC() { return (AccessControlContext) vm_generalMap_get("Global ACC"); } public static void replaceACCInClassLoader(Object o, AccessControlContext newACC) { ClassLoader cl = getClassLoaderOrSame(o); if (cl instanceof URLClassLoader) { try { setOpt(cl, "acc", newACC); try { setOpt(getOpt(cl, "ucp"), "acc", newACC); } catch (Throwable e) { printShortException(e); if (java10OrHigher()) if (addDefaultVMOption("--add-opens java.base/jdk.internal.loader=ALL-UNNAMED")) print("Please restart the OS"); } } catch (Throwable __e) { _handleException(__e); } } } public static String intToHex(int i) { return bytesToHex(intToBytes(i)); } public static Object findComponentPopupMenuListener_gen(final JComponent c) { return c == null ? null : swing(new F0() { public Object get() { try { return firstWithClassShortNamed("componentPopupMenu_Adapter", c.getMouseListeners()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret firstWithClassShortNamed('componentPopupMenu_Adapter, c.getMouseListeners..."; } }); } public static boolean jmenuItem_newThreads; public static JMenuItem jmenuItem(final String text) { return jMenuItem(text, null); } public static JMenuItem jmenuItem(final String text, final Object r) { return swing(new F0() { public JMenuItem get() { try { Pair p = jmenu_autoMnemonic(dropPrefix("[disabled] ", text)); JMenuItem mi = new JMenuItem(p.a); if (startsWith(text, "[disabled] ")) disableMenuItem(mi); if (p.b != 0) mi.setMnemonic(p.b); mi.addActionListener(jmenuItem_newThreads ? actionListenerInNewThread(r) : actionListener(r)); return mi; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Pair p = jmenu_autoMnemonic(dropPrefix(\"[disabled] \", text));\r\n JM..."; } }); } public static MenuItem menuItem(String text, final Object r) { MenuItem mi = new MenuItem(text); mi.addActionListener(actionListener(r)); return mi; } public static List filterNempty(Collection c) { List l = new ArrayList(); for (String x : unnull(c)) if (nempty(x)) l.add(x); return l; } public static String reverseString(String s) { return new StringBuilder(s).reverse().toString(); } public static Map> javaTok_cached_cache = synchronizedMRUCache(100); public static List javaTok_cached(String s) { List tok = javaTok_cached_cache.get(s); if (tok == null) javaTok_cached_cache.put(s, tok = javaTok(s)); return tok; } public static List indicesOfSubListIC(List x, List y) { List l = new ArrayList(); int i = 0; while (true) { int j = indexOfSubListIC(x, y, i); if (j < 0) break; l.add(j); i = j + 1; } return l; } public static void tokPrepend(List tok, int i, String s) { tok.set(i, s + tok.get(i)); } public static void tokAppend(List tok, int i, String s) { tok.set(i, tok.get(i) + s); } public static List javaTokPlusBrackets2(String s) { return tok_combineRoundCurlySquareBrackets_keep(javaTok(s)); } public static B mapGet(Map map, A a) { return map == null || a == null ? null : map.get(a); } public static B mapGet(A a, Map map) { return map == null || a == null ? null : map.get(a); } public static TreeSet mapToCISet(Object f, Iterable l) { TreeSet x = ciSet(); if (l != null) for (Object o : l) addIfNotNull(x, (String) callF(f, o)); return x; } public static Set filterCISet(Iterable c, Object pred) { Set x = ciSet(); if (c != null) for (String o : c) if (isTrue(callF(pred, o))) x.add(o); return x; } public static Set filterCISet(Object pred, Iterable c) { return filterCISet(c, pred); } public static boolean hasLetterOrDigit(String s) { return containsLetterOrDigit(s); } public static Set ciSetIntersection(Collection a, Collection b) { Set set = ciSet(); Set bSet = asCISet(b); for (String x : a) if (bSet.contains(x)) set.add(x); return set; } public static List javaTokWithBracketsPlusJavaTokC(String s) { return concatLists(javaTokPlusBracketsC(s), javaTokC(s)); } public static A firstOfPair(Pair p) { return p == null ? null : p.a; } public static Object vmGeneralMap_get(Object key) { return vm_generalMap_get(key); } public static String loadProgramTextFile(String name) { return loadTextFile(getProgramFile(name)); } public static String loadProgramTextFile(String progID, String name) { return loadTextFile(getProgramFile(progID, name)); } public static String loadProgramTextFile(String progID, String name, String defaultText) { return loadTextFile(getProgramFile(progID, name), defaultText); } public static String loadPage_utf8(URL url) { return loadPage_utf8(url.toString()); } public static String loadPage_utf8(String url) { loadPage_charset.set("UTF-8"); try { return loadPage(url); } finally { loadPage_charset.set(null); } } public static void saveTranspiledCode(String progID, String code) { File dir = getCodeProgramDir(progID); new File(dir, "Transpilation").delete(); saveGZTextFile(new File(dir, "Transpilation.gz"), code); } public static int findEndOfBlock(List cnc, int i) { int j = i + 2, level = 1, n = cnc.size(); while (j < n) { String t = cnc.get(j); if ("{".equals(t)) ++level; else if ("}".equals(t)) --level; if (level == 0) return j + 1; j += 2; } return n; } public static boolean eqGetOneOf(List l, int i, A... options) { return eqOneOf(get(l, i), options); } public static int leftScanModifiers(List tok, int i) { List mod = getJavaModifiers(); while (i > 1 && mod.contains(tok.get(i - 2))) i -= 2; return i; } public static File makeTempDir() { return (File) call(getJavaX(), "TempDirMaker_make"); } public static File linux_fileInRamDisk(String name) { if (!isLinux()) return null; File dir = newFile("/dev/shm"); if (dir.isDirectory()) return newFile(dir, name); return null; } public static boolean isMarkedAsSrcLib(String snippetID) { return snippetID != null && fileExists(javaxCodeDir("srclibs/" + psI(snippetID))); } public static Object hotwire_onCompile; public static boolean hotwire_serially; public static Lock hotwire_overInternalBot_lock = lock(); public static boolean hotwire_compileOnServer; public static Class hotwire_overInternalBot(String progID) { return hotwire_overInternalBot(progID, "main"); } public static Class hotwire_overInternalBot(String progID, String mainClass) { try { Pair p = hotwire_compile(progID); File jar = p.a; assertTrue(jar.getAbsolutePath(), jar.isFile()); List files = hotwire_collectJars(jar); JavaXClassLoader classLoader = hotwire_makeClassLoader(files); classLoader.progID = progID; return hotwire_finish(classLoader, progID, p.b, mainClass); } catch (Exception __e) { throw rethrow(__e); } } public static Pair hotwire_compile(String progID) { Pair p = hotwire_compileOnServer && !isLocalSnippetID(progID) ? compileSnippetThroughServer(progID) : CompilerBot.compileSnippet2(progID); Lock __1617 = hotwire_serially ? hotwire_overInternalBot_lock : null; lock(__1617); try { callF(hotwire_onCompile, p); return p; } finally { unlock(__1617); } } public static boolean preferCached = false; public static boolean loadSnippet_debug = false; public static ThreadLocal loadSnippet_silent = new ThreadLocal(); public static int loadSnippet_timeout = 30000; public static String loadSnippet(String snippetID) { try { if (snippetID == null) return null; return loadSnippet(parseSnippetID(snippetID), preferCached); } catch (Exception __e) { throw rethrow(__e); } } public static String loadSnippet(String snippetID, boolean preferCached) throws IOException { return loadSnippet(parseSnippetID(snippetID), preferCached); } public static String loadSnippet(long snippetID) { try { return loadSnippet(snippetID, preferCached); } catch (Exception __e) { throw rethrow(__e); } } public static String loadSnippet(long snippetID, boolean preferCached) throws IOException { String text; if (isLocalSnippetID(snippetID)) return loadLocalSnippet(snippetID); initSnippetCache(); text = DiskSnippetCache_get(snippetID); if (preferCached && text != null) return text; try { if (loadSnippet_debug && text != null) System.err.println("md5: " + md5(text)); String url = tb_mainServer() + "/getraw.php?id=" + snippetID + "&utf8=1"; if (nempty(text)) url += "&md5=" + md5(text); url += standardCredentials(); String text2 = loadSnippet_loadFromServer(url); boolean same = eq(text2, "==*#*=="); if (loadSnippet_debug) print("loadSnippet: same=" + same); if (!same) text = text2; } catch (RuntimeException e) { e.printStackTrace(); throw new IOException("Snippet #" + snippetID + " not found or not public"); } try { initSnippetCache(); DiskSnippetCache_put(snippetID, text); } catch (IOException e) { System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")"); } return text; } public static File DiskSnippetCache_dir; public static void initDiskSnippetCache(File dir) { DiskSnippetCache_dir = dir; dir.mkdirs(); } public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException { return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null); } public static File DiskSnippetCache_getFile(long snippetID) { return new File(DiskSnippetCache_dir, "" + snippetID); } public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException { saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet); } public static File DiskSnippetCache_getDir() { return DiskSnippetCache_dir; } public static void initSnippetCache() { if (DiskSnippetCache_dir == null) initDiskSnippetCache(getGlobalCache()); } public static String loadSnippet_loadFromServer(String url) { Integer oldTimeout = setThreadLocal(loadPage_forcedTimeout_byThread, loadSnippet_timeout); try { return isTrue(loadSnippet_silent.get()) ? loadPageSilently(url) : loadPage(url); } finally { loadPage_forcedTimeout_byThread.set(oldTimeout); } } public static void markAsSrcLib(String snippetID) { saveTextFile(javaxCodeDir("srclibs/" + psI(snippetID)), ""); } public static int latestInstalledJavaX() { File[] files = new File(userHome(), ".javax").listFiles(); int v = 0; if (files != null) for (File f : files) { Matcher m = Pattern.compile("x(\\d\\d\\d?)\\.jar").matcher(f.getName()); if (m.matches()) v = Math.max(v, Integer.parseInt(m.group(1))); } return v; } public static String addSuffix(String s, String suffix) { return s == null || s.endsWith(suffix) ? s : s + suffix; } public static List filesWithExtension(String ext, List files) { return filesEndingWith(files, addPrefixIfNotEmpty2(".", ext)); } public static List findAllFiles_noDirs(List dirs) { return findAllFiles_noDirs(asObjectArray(dirs)); } public static List findAllFiles_noDirs(Object... dirs) { List l = new ArrayList(); for (Object dir : dirs) { if (dir instanceof String && ((String) dir).endsWith("/.")) { for (File f : listFiles(dropSuffix("/.", (String) dir))) if (f.isFile()) l.add(f); } else findAllFiles_noDirs_impl(toFile(dir), l); } return l; } public static void findAllFiles_noDirs_impl(File dir, List l) { for (File f : listFiles(dir)) { if (f.isDirectory()) findAllFiles_noDirs_impl(f, l); else l.add(f); } } public static File[] listFiles(File dir) { File[] files = dir.listFiles(); return files == null ? new File[0] : files; } public static File[] listFiles(String dir) { return listFiles(new File(dir)); } public static List sortFilesByName(List l) { sort(l, new Comparator() { public int compare(File a, File b) { return stdcompare(a.getName(), b.getName()); } }); return l; } public static int deleteAllFilesInDirectory_minPathLength = 10; public static void deleteAllFilesInDirectory(File dir) { deleteAllFilesInDirectory(dir, false, false); } public static void deleteAllFilesInDirectory(File dir, boolean verbose, boolean testRun) { dir = getCanonicalFile(dir); assertTrue(f2s(dir), l(f2s(dir)) >= deleteAllFilesInDirectory_minPathLength); File[] files = dir.listFiles(); if (files == null) return; for (File f : files) { if (!isSymLink(f) && f.isDirectory()) deleteDirectory(f, verbose, testRun); else { if (verbose) print((testRun ? "Would delete " : "Deleting ") + f.getAbsolutePath()); if (!testRun) f.delete(); } } } public static Object callJavaX(String method, Object... args) { return callOpt(getJavaX(), method, args); } public static ClassLoader getClassLoaderOrSame(Object o) { return o instanceof ClassLoader ? (ClassLoader) o : getClassLoader(o); } public static void printShortException(Throwable e) { print(exceptionToStringShort(e)); } public static boolean java10OrHigher() { return parseFirstInt(javaVersion()) >= 10; } public static boolean addDefaultVMOption(String option) { String s = defaultVMArgs(), old = s; if (!s.contains(option)) s = trim(s + " " + option); if (eq(old, s)) return false; { setDefaultVMArgs(s); return true; } } public static byte[] intToBytes(int i) { return new byte[] { (byte) (i >>> 24), (byte) (i >>> 16), (byte) (i >>> 8), (byte) i }; } public static A firstWithClassShortNamed(String shortName, Iterable l) { if (l != null) for (A o : l) if (eq(shortClassName(o), shortName)) return o; return null; } public static A firstWithClassShortNamed(String shortName, A[] l) { if (l != null) for (A o : l) if (eq(shortClassName(o), shortName)) return o; return null; } public static JMenuItem jMenuItem(final String text) { return jmenuItem(text); } public static JMenuItem jMenuItem(String text, Object r) { return jmenuItem(text, r); } public static Pair jmenu_autoMnemonic(String s) { int i = indexOf(s, '&'); if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i + 1))) return pair(substring(s, 0, i) + substring(s, i + 1), (int) s.charAt(i + 1)); return pair(s, 0); } public static JMenuItem disableMenuItem(final JMenuItem mi) { if (mi != null) { swing(new Runnable() { public void run() { try { mi.setEnabled(false); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "mi.setEnabled(false);"; } }); } return mi; } public static ActionListener actionListenerInNewThread(final Object runnable) { return actionListenerInNewThread(runnable, null); } public static ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) { if (runnable instanceof ActionListener) return (ActionListener) runnable; return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { startThread("Action Listener", new Runnable() { public void run() { try { AutoCloseable __1766 = holdInstance(instanceToHold); try { callF(runnable); } finally { _close(__1766); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __1766 = holdInstance(instanceToHold); try {\r\n callF(runna..."; } }); } catch (Throwable __e) { messageBox(__e); } } }; } public static int indexOfSubListIC(List x, List y) { return indexOfSubListIC(x, y, 0); } public static int indexOfSubListIC(List x, List y, int i) { outer: for (; i + l(y) <= l(x); i++) { for (int j = 0; j < l(y); j++) if (neqic(x.get(i + j), y.get(j))) continue outer; return i; } return -1; } public static List tok_combineRoundCurlySquareBrackets_keep(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && eqOneOf(t, "{", "(", "[")) { int j = findEndOfBracketPart2(tok, i); l.add(joinSubList(tok, i, j)); i = j - 1; } else l.add(t); } return l; } public static boolean containsLetterOrDigit(String s) { for (int i = 0; i < l(s); i++) if (isLetterOrDigit(s.charAt(i))) return true; return false; } public static List javaTokPlusBracketsC(String s) { return codeTokens(javaTokPlusBrackets(s)); } public static void saveGZTextFile(File file, String contents) { try { File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = file.getPath() + "_temp"; File tempFile = new File(tempFileName); if (contents != null) { if (tempFile.exists()) try { String saveName = tempFileName + ".saved." + now(); copyFile(tempFile, new File(saveName)); } catch (Throwable e) { printStackTrace(e); } FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath()); GZIPOutputStream gos = new GZIPOutputStream(fileOutputStream); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(gos, "UTF-8"); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); gos.close(); fileOutputStream.close(); } if (file.exists() && !file.delete()) throw new IOException("Can't delete " + file.getPath()); if (contents != null) if (!tempFile.renameTo(file)) throw new IOException("Can't rename " + tempFile + " to " + file); } catch (Exception __e) { throw rethrow(__e); } } public static List getJavaModifiers_list = litlist("static", "abstract", "public", "private", "protected", "final", "native", "volatile", "synchronized", "transient"); public static List getJavaModifiers() { return getJavaModifiers_list; } public static Cache isLinux_cache = new Cache("isLinux_load"); public static boolean isLinux() { return isLinux_cache.get(); } public static Boolean isLinux_load() { return !isWindows() && !isMac() && !isAndroid(); } public static List hotwire_collectJars(File jar) { List libIDs = hotwire_libraryIDsFromJar_deleteJarOnFail(jar); List files = ll(jar); for (String libID : libIDs) files.add(loadLibraryOrSrcLib(libID)); return files; } public static Pair compileSnippetThroughServer(String progID) { String transpiledSrc = getServerTranspiled2(progID); String md5 = md5(transpiledSrc + "\n" + progID); File jar = CompilerBot.getJarFile(md5); if (jar == null || jar.length() <= 22) { byte[] jarData = null; try { jarData = loadBinaryPage("http://www.botcompany.de/jar/" + psI(progID) + "?md5=" + md5(transpiledSrc)); } catch (Throwable __e) { _handleException(__e); } if (!isJAR(jarData)) { print(bytesToHex(takeFirstOfByteArray(8, jarData))); print("fallback to CompilerBot: " + fromUtf8(takeFirstOfByteArray(80, jarData))); return CompilerBot.compileSnippet2(progID); } saveBinaryFile(jar, jarData); } return pair(jar, transpiledSrc); } public static String loadLocalSnippet(String snippetID) { return loadLocalSnippet(psI(snippetID)); } public static String loadLocalSnippet(long snippetID) { return loadTextFile(localSnippetFile(snippetID)); } public static List filesEndingWith(File dir, String suffix) { return listFilesWithSuffix(dir, suffix); } public static List filesEndingWith(List l, String suffix) { List out = new ArrayList(); for (File f : unnull(l)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix))) out.add(f); return out; } public static Object[] asObjectArray(List l) { return toObjectArray(l); } public static File toFile(Object o) { if (o instanceof File) return (File) o; if (o instanceof String) return new File((String) o); throw fail("Not a file: " + o); } public static File getCanonicalFile(File f) { try { return f == null ? null : f.getCanonicalFile(); } catch (Exception __e) { throw rethrow(__e); } } public static boolean isSymLink(File f) { return f != null && Files.isSymbolicLink(toPath(f)); } public static ClassLoader getClassLoader(Object o) { return o == null ? null : _getClass(o).getClassLoader(); } public static int parseFirstInt(String s) { return parseInt(jextract("", s)); } public static String javaVersion() { return System.getProperty("java.version"); } public static String defaultVMArgs() { return javaxDefaultVMArgs(); } public static void setDefaultVMArgs(String args) { String oldArgs = javaxDefaultVMArgs(); args = trim(args); if (neq(unnull(oldArgs), unnull(args))) { print(); print("Changing default VM arguments from"); print(" " + oldArgs); print("to"); print(" " + args); print(); saveTextFile(javaxDataDir("default-vm-args"), nullIfEmpty(args)); } } public static boolean isLetterOrDigit(char c) { return Character.isLetterOrDigit(c); } public static int findEndOfBracketPart2(List cnc, int i) { int j = i + 2, level = 1; while (j < cnc.size()) { if (eqOneOf(cnc.get(j), "{", "(", "[")) ++level; else if (eqOneOf(cnc.get(j), "}", ")", "]")) --level; if (level == 0) return j + 1; ++j; } return cnc.size(); } public static boolean isWindows() { return System.getProperty("os.name").contains("Windows"); } public static boolean isMac() { return System.getProperty("os.name").toLowerCase().contains("mac"); } public static List hotwire_libraryIDsFromJar_deleteJarOnFail(File jar) { try { return hotwire_libraryIDsFromJar(jar); } catch (Throwable _e) { jar.delete(); throw rethrow(_e); } } public static byte[] isJAR_magic = bytesFromHex("504B0304"); public static boolean isJAR(byte[] data) { return byteArrayStartsWith(data, isJAR_magic); } public static boolean isJAR(File f) { return isJAR(loadBeginningOfBinaryFile(f, l(isJAR_magic))); } public static byte[] takeFirstOfByteArray(byte[] b, int n) { return subByteArray(b, 0, n); } public static byte[] takeFirstOfByteArray(int n, byte[] b) { return takeFirstOfByteArray(b, n); } public static List listFilesWithSuffix(File dir, String suffix) { List l = new ArrayList(); for (File f : listFiles(dir)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix))) l.add(f); return l; } public static Path toPath(File f) { return f == null ? null : f.toPath(); } public static String jextract(String pat, String s) { return jextract(pat, javaTok(s)); } public static String jextract(String pat, List tok) { List tokpat = javaTok(pat); jfind_preprocess(tokpat); int i = jfind(tok, tokpat); if (i < 0) return null; int j = i + l(tokpat) - 2; return joinSubList(tok, i, j); } public static String javaxDefaultVMArgs() { File fileNew, fileOld; String text = loadTextFile(fileNew = javaxDataDir("default-vm-args")); if (text == null) { text = loadTextFile(fileOld = programFile("#1005850", "default-vm-args")); if (text != null) moveFile(fileOld, fileNew); } return trim(unnull(text)); } public static List hotwire_libraryIDsFromJar(File jar) { String dehlibs = unnull(loadTextFileFromZip(jar, "libraries")); return regexpExtractAll("\\d+", dehlibs); } public static byte[] subByteArray(byte[] b, int start) { return subByteArray(b, start, l(b)); } public static byte[] subByteArray(byte[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start == 0 && end == l(b)) return b; if (start >= end) return new byte[0]; byte[] x = new byte[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } public static File programFile(String name) { return prepareProgramFile(name); } public static File programFile(String progID, String name) { return prepareProgramFile(progID, name); } public static void moveFile(File a, File b) { if (!renameFile(a, b)) throw fail("File move failed: " + a + " to " + b); } public static List regexpExtractAll(String pat, String s) { if (s == null) return null; Matcher m = regexpMatcher(pat, s); List out = new ArrayList(); while (m.find()) out.add(m.group()); return out; } public static File prepareProgramFile(String name) { return mkdirsForFile(getProgramFile(name)); } public static File prepareProgramFile(String progID, String name) { return mkdirsForFile(getProgramFile(progID, name)); } public static boolean renameFile(File a, File b) { mkdirsForFile(b); return a.renameTo(b); } public static boolean renameFile(File a, String newName) { return renameFile(a, fileInSameDir(a, newName)); } public static class Cache { public Object maker; public A value; public long loaded; public static boolean debug; public long changeCount; public Lock lock = lock(); public Cache() { } public Cache(Object maker) { this.maker = maker; } public A get() { if (hasLock(lock)) return value; Lock __2108 = lock; lock(__2108); try { if (loaded == 0) { value = make(); changeCount++; loaded = sysNow(); } return value; } finally { unlock(__2108); } } public void clear() { Lock __2109 = lock; lock(__2109); try { if (debug && loaded != 0) print("Clearing cache"); value = null; changeCount++; loaded = 0; } finally { unlock(__2109); } } public void clear(double seconds) { Lock __2110 = lock; lock(__2110); try { if (seconds != 0 && loaded != 0 && sysNow() >= loaded + seconds * 1000) clear(); } finally { unlock(__2110); } } public void set(A a) { Lock __2111 = lock; lock(__2111); try { value = a; ++changeCount; loaded = sysNow(); } finally { unlock(__2111); } } public A make() { return (A) callF(maker); } } public static boolean hasLock(Lock lock) { return ((ReentrantLock) lock).isHeldByCurrentThread(); } }