Warning : session_start(): open(/var/lib/php/sessions/sess_ihql8gi38ckc3u6hf1gjldhb4h, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
// example use:
// auto open theories
import java.text.NumberFormat;
class main {
static void philosophyBot_autoOpenTheoriesHandler(PhilosophyBot1 bot) {
bot.addFactPreprocessor(s -> {
if (bot.matchString("auto open theories", s) == null) return false;
bot.autoOpenTheories();
return true;
});
}
static class PhilosophyBot1 {
static class LogicRule implements IFieldsToList, Transformable{
Object lhs;
Object rhs;
LogicRule() {}
LogicRule(Object lhs, Object rhs) {
this.rhs = rhs;
this.lhs = lhs;}
public String toString() { return "LogicRule(" + lhs + ", " + rhs + ")"; }
public boolean equals(Object o) {
if (!(o instanceof LogicRule)) return false;
LogicRule x = (LogicRule) o;
return eq(lhs, x.lhs) && eq(rhs, x.rhs);
}
public int hashCode() {
int h = 274479962;
h = boostHashCombine(h, _hashCode(lhs));
h = boostHashCombine(h, _hashCode(rhs));
return h;
}
public Object[] _fieldsToList() { return new Object[] {lhs, rhs}; }
public Object transformUsing(IF1 f) { return new LogicRule(f.get(lhs), f.get(rhs)); }
}
static class And implements IFieldsToList, Transformable{
Object a;
Object b;
And() {}
And(Object a, Object b) {
this.b = b;
this.a = a;}
public String toString() { return "And(" + a + ", " + b + ")"; }
public boolean equals(Object o) {
if (!(o instanceof And)) return false;
And x = (And) o;
return eq(a, x.a) && eq(b, x.b);
}
public int hashCode() {
int h = 65975;
h = boostHashCombine(h, _hashCode(a));
h = boostHashCombine(h, _hashCode(b));
return h;
}
public Object[] _fieldsToList() { return new Object[] {a, b}; }
public Object transformUsing(IF1 f) { return new And(f.get(a), f.get(b)); }
}
static class If implements IFieldsToList, Transformable{
Object condition;
Object thenBlock;
Object elseBlock;
If() {}
If(Object condition, Object thenBlock, Object elseBlock) {
this.elseBlock = elseBlock;
this.thenBlock = thenBlock;
this.condition = condition;}
public String toString() { return "If(" + condition + ", " + thenBlock + ", " + elseBlock + ")"; }
public boolean equals(Object o) {
if (!(o instanceof If)) return false;
If x = (If) o;
return eq(condition, x.condition) && eq(thenBlock, x.thenBlock) && eq(elseBlock, x.elseBlock);
}
public int hashCode() {
int h = 2365;
h = boostHashCombine(h, _hashCode(condition));
h = boostHashCombine(h, _hashCode(thenBlock));
h = boostHashCombine(h, _hashCode(elseBlock));
return h;
}
public Object[] _fieldsToList() { return new Object[] {condition, thenBlock, elseBlock}; }
public Object transformUsing(IF1 f) { return new If(f.get(condition), f.get(thenBlock), f.get(elseBlock)); }
}
static class For implements IFieldsToList, Transformable{
Object var;
Object condition;
Object body;
For() {}
For(Object var, Object condition, Object body) {
this.body = body;
this.condition = condition;
this.var = var;}
public String toString() { return "For(" + var + ", " + condition + ", " + body + ")"; }
public boolean equals(Object o) {
if (!(o instanceof For)) return false;
For x = (For) o;
return eq(var, x.var) && eq(condition, x.condition) && eq(body, x.body);
}
public int hashCode() {
int h = 70825;
h = boostHashCombine(h, _hashCode(var));
h = boostHashCombine(h, _hashCode(condition));
h = boostHashCombine(h, _hashCode(body));
return h;
}
public Object[] _fieldsToList() { return new Object[] {var, condition, body}; }
public Object transformUsing(IF1 f) { return new For(f.get(var), f.get(condition), f.get(body)); }
} // don't need var actually
static class ForIn implements IFieldsToList, Transformable{
Object var;
Object expr;
Object body;
ForIn() {}
ForIn(Object var, Object expr, Object body) {
this.body = body;
this.expr = expr;
this.var = var;}
public String toString() { return "ForIn(" + var + ", " + expr + ", " + body + ")"; }
public boolean equals(Object o) {
if (!(o instanceof ForIn)) return false;
ForIn x = (ForIn) o;
return eq(var, x.var) && eq(expr, x.expr) && eq(body, x.body);
}
public int hashCode() {
int h = 68065198;
h = boostHashCombine(h, _hashCode(var));
h = boostHashCombine(h, _hashCode(expr));
h = boostHashCombine(h, _hashCode(body));
return h;
}
public Object[] _fieldsToList() { return new Object[] {var, expr, body}; }
public Object transformUsing(IF1 f) { return new ForIn(f.get(var), f.get(expr), f.get(body)); }
}
static class While implements IFieldsToList, Transformable{
Object condition;
Object body;
While() {}
While(Object condition, Object body) {
this.body = body;
this.condition = condition;}
public String toString() { return "While(" + condition + ", " + body + ")"; }
public boolean equals(Object o) {
if (!(o instanceof While)) return false;
While x = (While) o;
return eq(condition, x.condition) && eq(body, x.body);
}
public int hashCode() {
int h = 83548945;
h = boostHashCombine(h, _hashCode(condition));
h = boostHashCombine(h, _hashCode(body));
return h;
}
public Object[] _fieldsToList() { return new Object[] {condition, body}; }
public Object transformUsing(IF1 f) { return new While(f.get(condition), f.get(body)); }
}
// native predicate return type (Bool/SS/null)
// like a native predicate, but doesn't return anything
static class CodeFragment {
String head;
IVF2, Env> body;
boolean keepBrackets = false;
CodeFragment(String head, IVF2, Env> body, boolean keepBrackets) {
this.keepBrackets = keepBrackets;
this.body = body;
this.head = head;}
CodeFragment(String head, IVF2, Env> body) {
this.body = body;
this.head = head;}
public String toString() { return stdToString(this); }
}
static class Env {
boolean wantAlternatives = false;
boolean wantAlternatives() { return wantAlternatives; }
}
static class WithAlternative implements IFieldsToList{
IF0 alternative;
Object result;
WithAlternative() {}
WithAlternative(IF0 alternative, Object result) {
this.result = result;
this.alternative = alternative;}
public String toString() { return "WithAlternative(" + alternative + ", " + result + ")"; }
public boolean equals(Object o) {
if (!(o instanceof WithAlternative)) return false;
WithAlternative x = (WithAlternative) o;
return eq(alternative, x.alternative) && eq(result, x.result);
}
public int hashCode() {
int h = -1195262233;
h = boostHashCombine(h, _hashCode(alternative));
h = boostHashCombine(h, _hashCode(result));
return h;
}
public Object[] _fieldsToList() { return new Object[] {alternative, result}; }
}
// body takes variable mapping
// body can return
// Bool => immediate result (ok or fail)
// SS => variable mapping
// WithAlternative
// Iterator
// null => not applicable
// For "for $x in ..." statements, return a Iterable?
static class NativePredicate implements IFieldsToList{
static final String _fieldOrder = "head body";
String head;
IF2, Env, Object> body;
NativePredicate() {}
NativePredicate(String head, IF2, Env, Object> body) {
this.body = body;
this.head = head;}
public String toString() { return "NativePredicate(" + head + ", " + body + ")"; }
public boolean equals(Object o) {
if (!(o instanceof NativePredicate)) return false;
NativePredicate x = (NativePredicate) o;
return eq(head, x.head) && eq(body, x.body);
}
public int hashCode() {
int h = 1520196416;
h = boostHashCombine(h, _hashCode(head));
h = boostHashCombine(h, _hashCode(body));
return h;
}
public Object[] _fieldsToList() { return new Object[] {head, body}; }
}
// procedures are a list of statements
transient String program;
transient int maxRounds = 1000;
transient Set facts = linkedCISet();
transient Set originalFacts;
transient LinkedHashSet logicRules = new LinkedHashSet();
transient AllOnAll rulesOnFacts = new AllOnAll();
transient AllOnAll codeOnFacts = new AllOnAll();
transient AllOnAll, String> anyCodeOnFacts = new AllOnAll();
transient List proceduresToRun = new ArrayList();
// parsed procedures
transient long proceduresExecuted;
transient List nativePredicates = new ArrayList();
transient boolean debugNativeCalls = true, debugAllCmds = true;
transient List onProcedureEnded = new ArrayList();
transient boolean printNonMatches, debugContradictionChecks;
transient boolean standardImportsLoaded = false;
// return true when you handled adding the rule
transient List> logicRulePreprocessors = new ArrayList();
// return true when you handled adding the fact
transient List> factPreprocessors = new ArrayList();
// extra stuff that is done every round
transient List extraLogicOperations = new ArrayList();
transient Set vars = litciset("x", "y", "z");
PhilosophyBot1() {
// find contradictions
anyCodeOnFacts.newA(fact -> {
Boolean b = checkNativeCondition(fact);
if (debugContradictionChecks)
print("Fact check: " + b + " - " + fact);
if (isFalse(b))
addFact("contradiction");
});
}
PhilosophyBot1(String program) { this();
this.program = program; }
void addRule(String s) {
Pair p = tok_splitAtDoubleArrow_pair(s);
if (p == null) print("addRule failed: " + s);
addLogicRule(new LogicRule(splitAtAmpersand2(p.a), splitAtAmpersand2(p.b)));
}
void addRules(Iterable l) {
for (String s : unnull(l)) addRule(s);
}
void addLogicRule(LogicRule rule) {
for (IF1 p : logicRulePreprocessors)
if (p.get(rule)) return; // has been preprocessed
// is LHS a native predicate? then eval immediately
// TODO: multiple conditions
Boolean b = checkConditionOpt(rule.lhs);
if (isFalse(b)) return; // drop rule
if (isTrue(b))
addFacts_possibleAnd(rule.rhs);
if (logicRules.add(rule)) {
print("Got logic rule", rule);
rulesOnFacts.newA(rule); // to combine it with the facts
}
}
void addFacts(Iterable l) {
for (String fact : unnull(l)) addFact(fact);
}
void addFact(String fact) {
fact = trim(fact);
if (empty(fact)) return;
fact = tok_deRoundBracket(fact);
for (IF1 p : factPreprocessors)
if (p.get(fact)) return; // has been preprocessed
// Check if it's a procedure
List tok = mainTokenize(fact);
if (countCodeTokens(tok) == 2 && firstTokenEqic(tok, "proc")
&& isCurlyBracketed(getCodeToken(tok, 1))) { try {
// It's a procedure!
String proc = uncurly_keepSpaces(getCodeToken(tok, 1));
if (proceduresToRun.add(parseProcedure(proc))) {
print("Got procedure:");
print(indentx("> ", proc));
}
} catch (Throwable __e) { _handleException(__e); }} /*else if (countCodeTokens(tok) == 2 && firstTokenEqic(tok, "java")
&& isCurlyBracketed(getCodeToken(tok, 1))) pcall {
// It's Java code
}*/ else // It's a fact, not a procedure
if (facts.add(fact)) {
print("Got fact: " + fact);
rulesOnFacts.newB(fact); // to combine it with the rules
codeOnFacts.newB(fact);
anyCodeOnFacts.newB(fact);
}
}
void addFacts_possibleAnd(Object o) {
if (o instanceof And) {
Object a = ((And) o).a;
Object b = ((And) o).b;
addFacts_possibleAnd(a);
addFacts_possibleAnd(b);
} else if (o != null)
addFact((String) o);
}
void runProcedure(String proc) { try {
print("Running procedure.");
runParsedProcedure(parseProcedure(proc));
} catch (Throwable __e) { _handleException(__e); }}
void runParsedProcedure(List commands) {
runParsedProcedure(commands, proceduresToRun);
}
void runParsedProcedure(List commands, List whereToPostCode) {
++proceduresExecuted;
Env env = new Env();
List remainingCommands = cloneLinkedList(commands);
Object cmd;
while ((cmd = popFirst_ping(remainingCommands)) != null) {
if (cmd instanceof List) { runParsedProcedure(((List) cmd)); continue; }
if (cmd instanceof Runnable) { ((Runnable) cmd).run(); continue; }
if (debugAllCmds)
print("Running cmd: " + sfu(cmd));
if (cmd instanceof If) {
Object condition = ((If) cmd).condition;
Object thenBlock = ((If) cmd).thenBlock;
Object elseBlock = ((If) cmd).elseBlock;
Object blockToRun = checkCondition(condition) ? thenBlock : elseBlock;
runParsedProcedure(ll(blockToRun));
} else if (cmd instanceof For) {
Object var = ((For) cmd).var;
Object condition = ((For) cmd).condition;
Object body = ((For) cmd).body;
// make a new logic rule and add it
// assume the variable is globally declared as a variable
addLogicRule(new LogicRule(condition, "proc {\n" + body + "\n}"));
} else if (cmd instanceof While) {
Object condition = ((While) cmd).condition;
Object body = ((While) cmd).body;
boolean b = checkCondition(condition);
if (!b) continue;
whereToPostCode.add(ll(body, cmd));
} else if (cmd instanceof ForIn && ((ForIn) cmd).var instanceof String && ((ForIn) cmd).expr instanceof String) {
String var = (String) (((ForIn) cmd).var);
String expr = (String) (((ForIn) cmd).expr);
Object body = ((ForIn) cmd).body;
// XXX
Object result = runNativePredicate(expr, new Env());
if (!(result instanceof Iterable)) {
print("Warning: result of " + expr + " not iterable (" + shortClassName(result) + ")");
continue;
}
Iterator it = iterator((Iterable) result);
Runnable step = new Runnable() { public void run() { try {
if (!it.hasNext()) return;
String value = str(it.next());
Map map = litcimap(var, value);
Object body2 = replaceVars(body, map);
//print("ForIn: " + map + " => " + body2);
whereToPostCode.add(ll(body2, this));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext()) return;\r\n String value = str(it.next());\r\n ..."; }};
step.run();
} else if (cmd instanceof String) {
Object result = runNativePredicate(((String) cmd), env);
if (result != null) {
result = unpackWithAlternativeOrIterator(result);
if (isFalse(result)) return;
if (isTrueOpt(result)) continue;
Map mapping = (Map) result; // assume it's a variable mapping
// apply to all remaining commands and continue
List remainingCommands2 = mapToLinkedList(remainingCommands,
c -> replaceVars(c, mapValues("optRound",mapping)));
print("Applying var mapping " + mapping + " to " + remainingCommands
+ " => " + remainingCommands2);
remainingCommands = remainingCommands2;
} else
addFact(((String) cmd));
} else if (cmd != null)
throw fail("Unimplemented command: " + cmd);
}
pcallFAll(onProcedureEnded, commands); // notify listeners
}
// return var mapping (SS), Bool or null for no matching predicate
// or result verbatim (e.g. Iterable)
Object runNativePredicate(String s, Env env) {
for (NativePredicate np : nativePredicates) {
Map map = zipIt(np.head, s);
if (map != null) {
Object result = np.body.get(mapValues("tok_deRoundBracket",map), env);
if (debugNativeCalls)
print("Native predicate result: " + np.head + " => " + result);
if (result instanceof Map && nempty(map)) {
result = mapKeys((Map) result, var -> lookupOrKeep(map, var));
if (debugNativeCalls)
print("Rewrote native predicate result: " + result);
}
{ Object __1= result; if (__1 != null) return __1; }
} else
if (printNonMatches)
print("Non-match: " + quote(np.head) + " / " + quote(s));
}
return null;
}
// returns false if unknown
boolean checkCondition(Object o) {
return isTrue(checkConditionOpt(o));
}
// returns null if unknown
Boolean checkConditionOpt(Object o) {
if (o instanceof String) {
if (contains(facts, ((String) o))) return true;
{ Boolean b = checkNativeCondition(((String) o)); if (b != null) return b; }
}
//print("Ignoring condition: " + o);
return null;
}
Boolean checkNativeCondition(String o) {
Object result = runNativePredicate(o, new Env());
result = unpackWithAlternativeOrIterator(result);
if (result instanceof Boolean) return ((Boolean) result);
if (result instanceof Map) return true; // TODO
return null;
}
boolean parsePythonesqueProcedure_debug = false;
List parsePythonesqueProcedure(String proc) {
//printStruct(proc);
proc = withoutLinesEmptyAfterTrim(proc);
//printStruct(proc);
//proc = autoUnindent(proc);
proc = autoUnindent_honoringBrackets(proc);
//printStruct(proc);
//print(indentx("> ", proc));
List l = groupPythonStyleIndents_honoringBrackets(proc);
//pnl("unpythonized ", l);
List out = new ArrayList();
If lastIf = null;
for (int i = 0; i < l(l); i++) {
String s = l.get(i);
List tok = javaTokWithBrackets(s);
if (eqic(firstCodeToken(tok), "if")) {
assertEquals(s, ":", getCodeToken(tok, 2));
out.add(lastIf = new If(deRoundBracket(getCodeToken(tok, 1)),
parsePythonesqueProcedure(joinSubList(tok, 3*2)), null));
continue;
}
if (eqic(firstCodeToken(tok), "unless")) {
assertEquals(s, ":", getCodeToken(tok, 2));
out.add(lastIf = new If(deRoundBracket(getCodeToken(tok, 1)),
null, parsePythonesqueProcedure(joinSubList(tok, 3*2))));
continue;
}
if (eqic(firstCodeToken(tok), "while")) {
assertEquals(s, ":", getCodeToken(tok, 2));
out.add(new While(deRoundBracket(getCodeToken(tok, 1)),
parsePythonesqueProcedure(joinSubList(tok, 3*2))));
continue;
}
if (eqic(firstCodeToken(tok), "else") && eqic(secondCodeToken(tok), "if")) {
Object last = last(out);
if (lastIf == null) throw fail("Else if without if");
assertEquals(s, ":", getCodeToken(tok, 3));
lastIf.elseBlock = lastIf = new If(deRoundBracket(getCodeToken(tok, 2)),
parsePythonesqueProcedure(joinSubList(tok, 4*2)), null);
continue;
}
if (eqic(firstCodeToken(tok), "else")) {
Object last = last(out);
if (lastIf == null) throw fail("Else without if");
assertEquals(s, ":", getCodeToken(tok, 1));
lastIf.elseBlock = joinSubList(tok, 2*2);
continue;
}
lastIf = null;
if (eqic(firstCodeToken(tok), "for")) {
if (eq(getCodeToken(tok, 2), "in")) {
int idx = indexOf(tok, ":");
assertTrue(s, idx >= 0);
String var = getCodeToken(tok, 1);
String expr = joinSubList(tok, 3*2+1, idx-1);
Object body = parsePythonesqueProcedure(joinSubList(tok, idx+1));
out.add(new ForIn(var, expr, body));
} else {
assertEquals(s, ":", getCodeToken(tok, 2));
String cond = getCodeToken(tok, 1);
// cond looks like: "(y | x has a y)"
cond = deRoundBracket(cond);
List tok2 = javaTok(cond);
assertEquals(cond, "|", getCodeToken(tok2, 1));
String var = assertIdentifier(cond, getCodeToken(tok2, 0));
String actualCondition = trimJoinSubList(tok2, 2*2+1);
out.add(new For(var, actualCondition, parsePythonesqueProcedure(joinSubList(tok, 3*2))));
}
} else
out.add(s);
}
if (parsePythonesqueProcedure_debug)
pnl("Parsed procedure ", out);
return out;
}
List parseProcedure(String s) {
return parsePythonesqueProcedure(s);
}
Object splitAtAmpersand2(String s) {
List l = tok_splitAtAmpersand(s);
if (l(l) == 1) return s;
return new And(first(l), splitAtAmpersand2(join(" & ", dropFirst(l))));
}
// "zip" a condition with a fact (match word-by-word)
Map zipIt(String cond, String fact) {
Map map = zipIt_keepBrackets(cond, fact);
if (map == null) return null; // no match
return mapValues("tok_deRoundOrCurlyBracket",map);
}
Map zipIt_deBracket(String pat, String s) {
Map map = zipIt(pat, s);
return map == null ? null : mapValues("tok_deRoundOrCurlyBracket",map);
}
// "zip" a condition with a fact (match word-by-word)
Map zipIt_keepBrackets(String cond, String fact) {
Map map = gazelle_deepZip_keepBrackets(cond, fact);
if (map == null) return null; // no match
if (!all(keys(map), s -> isVar(s))) return null; /*with print("Non-variable changes, exiting")*/;
return map;
}
boolean isVar(String s) {
return s != null &&
(vars.contains(s) || s.startsWith("var_") || isDollarVar(s));
}
Object replaceVars(Object o, Map map) {
if (empty(map)) return o;
return transform(x -> replaceVars_base(x, map), o);
}
Object replaceVars_base(Object o, Map map) {
if (o instanceof String)
return join(replaceCodeTokensUsingMap(javaTok(((String) o)), map));
return null;
}
// if f returns null, go through structure
Object transform(IF1 f, Object o) {
if (o == null) return null;
ping();
{ Object __2= f.get(o); if (__2 != null) return __2; }
if (o instanceof Transformable)
return ((Transformable) o).transformUsing(x -> transform(f, x));
if (o instanceof List)
return map(x -> transform(f, x), ((List) o));
throw fail("Don't know how to transform: " + className(o));
}
void applyLogicRuleToFact(LogicRule rule, String fact) {
Object lhs = rule.lhs, rhs = rule.rhs;
Object cond, remaining = null;
if (lhs instanceof And) {
Object a = ((And) lhs).a;
Object b = ((And) lhs).b;
cond = a;
remaining = b;
} else
cond = lhs;
// now we match the condition with the fact
Map map = zipIt_keepBrackets((String) cond, fact);
if (map == null) {
if (printNonMatches)
print("Non-match: " + quote(cond) + " / " + quote(fact));
return; // no match
}
// Now we have a proper mapping with the keys being variables!
print("Match: " + quote(cond) + " / " + quote(fact));
// drop round brackets
// XXX? map = mapValues tok_deRoundBracket(map);
// Apply mapping to right hand side
Object rhs_replaced = replaceVars(rhs, map);
print("rhs_replaced", rhs_replaced);
if (remaining == null) {
// Add as fact
addFacts_possibleAnd(rhs_replaced);
} else {
// Apply mapping to remaining condition
Object remaining_replaced = replaceVars(remaining, map);
addLogicRule(new LogicRule(remaining_replaced, rhs_replaced));
}
}
public void run() {
parseProgram();
think();
}
boolean smartParser1_verbose = false;
void smartParser1(String program) {
// split into paragraphs and unindent
List paragraphs = map(s -> withoutLeadingLinesEmptyAfterTrim_autoUnindent(rtrim(s)), tok_splitAtEmptyLines(program));
if (smartParser1_verbose) print("Got " + n2(paragraphs, "parapraph"));
// print the parapraphs
if (smartParser1_verbose) print(joinWithEmptyLines(map(s -> indentx("> ", s), paragraphs)));
// throw away comment-only and quoted paragraphs (assume it's a title)
List paragraphs2 = antiFilter(paragraphs, s ->
isSingleLine(trim(s)) && isQuoted(trim(s)) || countJavaTokens(s) == 0
|| endsWith(rtrim(s), "----"));
if (smartParser1_verbose) print("Got " + n2(paragraphs2, "filtered paragraph"));
if (smartParser1_verbose) print(joinWithEmptyLines(map(s -> indentx("> ", s), paragraphs2)));
// find fact paragraphs
if (smartParser1_verbose) print(map("allLinesAreUnindented",paragraphs2));
Pair, List> p1 = filterAntiFilter(s ->
!isSingleLine(trim(s)) && allLinesAreUnindented(s), paragraphs2);
List multiFactParagraphs = p1.a, paragraphs3 = p1.b;
for (String para : multiFactParagraphs)
for (String s : tlft(para))
addFact(s);
// find logic rules
List paragraphs4 = new ArrayList();
for (String para : paragraphs3) {
Pair p = splitAtDoubleArrow_pair(para);
if (p == null) { paragraphs4.add(para); continue; }
addLogicRule(new LogicRule(splitAtAmpersand2(p.a), splitAtAmpersand2(p.b)));
}
if (smartParser1_verbose) pnlStruct("Unparsed - assuming facts", paragraphs4);
// assume the unparsed stuff consists of facts
for (String para : paragraphs4)
addFact(para);
}
void parseProgram() {
loadProgram(program);
}
void loadProgram(String program) {
smartParser1(program);
}
boolean doSomeLogic() {
boolean anyAction = false;
Pair p;
while ((p = rulesOnFacts.next()) != null) {
ping();
anyAction = true;
//print("Combination: " + p);
applyLogicRuleToFact(p.a, p.b);
}
Pair p2;
while ((p2 = codeOnFacts.next()) != null) {
ping();
anyAction = true;
//print("Combination: " + p2);
applyCodeFragmentToFact(p2.a, p2.b);
}
Pair, String> p3;
while ((p3 = anyCodeOnFacts.next()) != null) {
ping();
anyAction = true;
//print("Combination: " + p3);
pcallF(p3.a, p3.b);
}
return anyAction;
}
void applyCodeFragmentToFact(CodeFragment cf, String fact) {
Map map = cf.keepBrackets ? zipIt_keepBrackets(cf.head, fact) : zipIt(cf.head, fact);
if (map != null)
cf.body.get(mapValues("tok_deRoundBracket",map), new Env());
}
// indicator for end of thought process (when this stays stable)
long size() {
return l(logicRules) + l(facts) + proceduresExecuted;
}
void think() {
if (originalFacts == null) originalFacts = cloneCISet(facts);
int round = 0;
while (round++ < maxRounds) { ping();
long lastSize = size();
print("Logic round " + round + ", size: " + lastSize);
while (doSomeLogic() && round++ < maxRounds) {}
for (List proc : getAndClearList(proceduresToRun))
{ ping(); runParsedProcedure(proc); }
callFAll(extraLogicOperations);
if (size() == lastSize) {
print("No changes, exiting");
break;
}
}
// We're done logicking, so print all the facts gathered
Collection madeFacts = factsDeduced();
pnlWithHeading("Facts I deduced", madeFacts);
// Print say () and print () separately
List output = new ArrayList();
for (String fact : madeFacts) {
List tok = mainTokenize(fact);
if (countCodeTokens(tok) == 2 && eqicOneOf(getCodeToken(tok, 0), "print", "say"))
// For the user, we print without all the round brackets
output.add(tok_dropRoundBrackets(getCodeToken(tok, 1)));
}
pnlWithHeading("Bot Output", output);
}
void addNativePredicate(String head, IF0 body) {
nativePredicates.add(new NativePredicate(head, (map, env) -> body.get()));
}
void addNativePredicate(String head, IF1, Object> body) {
nativePredicates.add(new NativePredicate(head, (map, env) -> body.get(map)));
}
void addNativePredicate(String head, IF2, Env, Object> body) {
nativePredicates.add(new NativePredicate(head, body));
}
// when you only need one result
Object unpackWithAlternativeOrIterator(Object result) {
if (result instanceof Iterator) return first((Iterator) result);
if (result instanceof WithAlternative) return ((WithAlternative) result).result;
return result;
}
void onFactDo(String head, IVF2, Env> body) {
codeOnFacts.newA(new CodeFragment(head, body));
}
void onFactDo_keepBrackets(String head, IVF2, Env> body) {
codeOnFacts.newA(new CodeFragment(head, body, true));
}
List filterByPattern(String pat, Iterable items) {
return filter(items, i -> zipIt(pat, i) != null);
}
// pat = pattern with variables
// results are mappings with debracketed values
List> matchFacts(String pat) {
return matchStrings(pat, facts);
}
Map matchString(String pat, String input) {
return zipIt_deBracket(pat, input);
}
List> matchStrings(String pat, Iterable items) {
List> out = new ArrayList();
for (String s : items) {
Map map = zipIt_deBracket(pat, s);
if (map != null)
out.add(map);
}
return out;
}
List>> matchFacts2(String pat) {
return matchStrings2(pat, facts);
}
// returns items too
List>> matchStrings2(String pat, Iterable items) {
List>> out = new ArrayList();
for (String s : items) {
Map map = zipIt_deBracket(pat, s);
if (map != null)
out.add(pair(s, map));
}
return out;
}
List matchFacts(String var, String pat) {
return map(matchFacts(pat), map -> map.get(var));
}
// pat = pattern with variables
// results are mappings with debracketed values
List> matchFacts_keepBrackets(String pat) {
List> out = new ArrayList();
for (String fact : facts) {
Map map = zipIt_keepBrackets(pat, fact);
if (map != null)
out.add(map);
}
return out;
}
void openAllTheories() {
for (Map map : matchFacts_keepBrackets("theory $x $y"))
openTheory(tok_deRoundOrCurlyBracket(map.get("$x")), map.get("$y"));
}
void openTheory(String name, String body) {
//print("Raw theory: " + quote(s));
loadProgram(withoutLeadingLinesEmptyAfterTrim_autoUnindent(tok_deRoundOrCurlyBracket_keepFirstSpacing(body)));
print("Opened theory " + name);
}
void autoOpenTheories() {
onFactDo_keepBrackets("theory $x $y", (map, env) -> openTheory(tok_deRoundOrCurlyBracket(map.get("$x")), map.get("$y")));
}
// returns number of expectations checked
int checkExpectations() {
int n = 0;
// check if all expect (...) facts are met
for (Map map : matchFacts("expect $x")) {
assertContains(facts, firstValue(map));
++n;
}
// check if all don't expect (...) facts are met
for (Map map : matchFacts("don't expect $x")) {
assertDoesntContain(facts, firstValue(map));
++n;
}
return n;
}
void standardImports() {
if (standardImportsLoaded) return;
standardImportsLoaded = true;
registerImport("math", () -> philosophyBot1_math(this));
registerImport("bool", () -> philosophyBot1_bool(this));
registerImport("or", () -> philosophyBot1_orHandler(this));
registerImport("iota", () -> philosophyBot1_iotaHandler(this));
registerImport("tlft_honoringBrackets", () ->
addNativePredicate("tlft_honoringBrackets $x",
map -> print("tlft output",
tlft_honoringBrackets($x(map)))));
addNativePredicate("printNonMatches", () -> { printNonMatches = true; return true; });
}
void addFactPreprocessor(IF1 f) {
factPreprocessors.add(f);
}
void registerImport(String name, Runnable handler) {
String line = "import " + name;
factPreprocessors.add(s -> {
if (eqic(s, line)) {
print("Importing " + name);
handler.run();
return true;
}
return false;
});
}
boolean hasFact(String fact) {
return contains(facts, fact);
}
boolean hasContradiction() { return hasFact("contradiction"); }
List mainTokenize(String s) {
return javaTokWithBrackets(s);
}
// sanitize untrusted input - overly safe version
String sanitizeInput(String s) {
return joinWithSpace(antiFilter(words2_plusApostrophe(s), w -> isVar(w)));
}
void deleteFacts(Iterable l) {
Set set = asCISet(l);
facts = filterCISet(facts, f -> !contains(set, f));
}
Collection factsDeduced() {
return listMinusList(facts, originalFacts);
}
boolean containsDollarVars(Object o) {
// abuse transform function
Flag flag = new Flag();
withCancelPoint(cp -> {
transform(x -> {
if (x instanceof String) {
if (main.containsDollarVars(((String) x))) {
flag.raise();
cancelTo(cp);
}
return ((String) x);
}
return null;
}, o);
});
return flag.get();
}
List allLogicRulesWithoutLHSVars() {
return filter(logicRules, r -> !containsDollarVars(leftmostCondition(r.lhs)));
}
Object leftmostCondition(Object o) {
while (o instanceof And) o = ((And) o).a;
return o;
}
}
static interface IF0 {
A get();
}static interface IFieldsToList {
Object[] _fieldsToList();
}static interface IF2 {
C get(A a, B b);
}static class AllOnAll {
List aList = new ArrayList();
List bList = new ArrayList();
List> todo = new LinkedList();
List> todo2 = new LinkedList();
synchronized void newA(A a) {
add(aList, a);
addPair(todo, intRange_last(aList), intRange(0, l(bList)));
}
synchronized void newAs(Iterable l) {
for (A a : unnull(l)) newA(a);
}
synchronized void newB(B b) {
add(bList, b);
addPair(todo, intRange(0, l(aList)), intRange_last(bList));
}
synchronized void newBs(Iterable l) {
for (B b : unnull(l)) newB(b);
}
synchronized Pair next() {
while (empty(todo2)) {
if (empty(todo)) return null;
Pair p = popFirst(todo);
addAll(todo2, outerProduct_pairs(subList(aList, p.a), subList(bList, p.b)));
}
return popFirst(todo2);
}
}static interface IF1 {
B get(A a);
}static interface Transformable {
Object transformUsing(IF1 f);
}
static interface IVF1 {
void get(A a);
}static interface IVF2 {
void get(A a, B b);
}/** this class is fully thread-safe */
static class Flag implements Runnable {
private boolean up = false;
/** returns true if flag was down before (i.e. flag was actually raised right now) */
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;
}
boolean get() { return isUp(); }
public String toString() {
return isUp() ? "up" : "down";
}
// currently does a semi-active wait with latency = 50 ms
public void waitForThisOr(Flag otherFlag) { try {
while (!isUp() && !otherFlag.isUp())
Thread.sleep(50);
} catch (Exception __e) { throw rethrow(__e); } }
public void run() { raise(); }
}static class Pair implements Comparable> {
A a;
B b;
Pair() {}
Pair(A a, B b) {
this.b = b;
this.a = a;}
public int hashCode() {
return hashCodeFor(a) + 2*hashCodeFor(b);
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Pair)) return false;
Pair t = (Pair) o;
return eq(a, t.a) && eq(b, t.b);
}
public String toString() {
return "<" + a + ", " + b + ">";
}
public int compareTo(Pair p) {
if (p == null) return 1;
int i = ((Comparable ) a).compareTo(p.a);
if (i != 0) return i;
return ((Comparable) b).compareTo(p.b);
}
}
final static class IntRange {
int start, end;
IntRange() {}
IntRange(int start, int end) {
this.end = end;
this.start = start;}
public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
int length() { return end-start; }
static String _fieldOrder = "start end";
public String toString() { return "[" + start + ";" + end + "]"; }
}
static boolean eq(Object a, Object b) {
return a == b || (a == null ? b == null : b != null && a.equals(b));
}
static int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}
static int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static String stdToString(Object o) {
return standard_toString(o);
}
static Set linkedCISet() {
return new LinkedTreeSet(ciSet());
}
static TreeSet litciset(String... items) {
TreeSet set = caseInsensitiveSet();
for (String a : items) set.add(a);
return set;
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
static boolean print_silent = false; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal print_byThread; // special handling by thread - prefers F1
static volatile Object print_allThreads;
static volatile Object print_preprocess;
static void print() {
print("");
}
static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
// slightly overblown signature to return original object...
static A print(A o) {
ping_okInCleanUp();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null) f = print_allThreads;
if (f != null)
// We do need the general callF machinery here as print_byThread is sometimes shared between modules
if (isFalse(
f instanceof F1 ? ((F1) f).get(s) :
callF(f, s))) return;
print_raw(s);
}
static void print_raw(String s) {
if (print_preprocess != null) s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static void print_autoRotate() {
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static Pair tok_splitAtDoubleArrow_pair(String s) {
return splitAtDoubleArrow_pair(s);
}
static Pair tok_splitAtDoubleArrow_pair(List tok) {
return splitAtDoubleArrow_pair(tok);
}
static String unnull(String s) {
return s == null ? "" : s;
}
static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
//ifclass Symbol
static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
if (o instanceof ThreadLocal) // TODO: remove this
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(CharSequence s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
if (o instanceof byte[]) return empty((byte[]) o);
if (o == null) return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(Iterator i) { return i == null || !i.hasNext(); }
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static boolean empty(byte[] a) { return a == null || a.length == 0; }
static boolean empty(short[] a) { return a == null || a.length == 0; }
static boolean empty(File f) { return getFileSize(f) == 0; }
static String tok_deRoundBracket(String s) {
return tok_isRoundBracketed(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
}
static int countCodeTokens(String s) {
return countTokens(s);
}
static int countCodeTokens(List tok) {
return countTokens(tok);
}
static boolean firstTokenEqic(List tok, String t) {
return eqic(get(tok, 1), t);
}
static boolean isCurlyBracketed(String s) {
return isCurlyBraced(s);
}
static String getCodeToken(List tok, int i) {
return get(tok, i*2+1);
}
static String uncurly_keepSpaces(String s) {
return tok_unCurlyBracket_keepSpaces(s);
}
static String indentx(String s) {
return indentx(indent_default, s);
}
static String indentx(int n, String s) {
return dropSuffix(repeat(' ', n), indent(n, s));
}
static String indentx(String indent, String s) {
return dropSuffix(indent, indent(indent, s));
}
static volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll("printStackTrace2"));
static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3); // not using pcall here - it could lead to endless loops
}
}
static LinkedList cloneLinkedList(Iterable l) {
return l instanceof Collection ? cloneLinkedList((Collection) l) : asLinkedList(l);
}
static LinkedList cloneLinkedList(Collection l) {
if (l == null) return new LinkedList();
synchronized(collectionMutex(l)) {
return new LinkedList (l);
}
}
static A popFirst_ping(List l) {
ping();
return popFirst(l);
}
static A popFirst_ping(Collection l) {
ping();
return popFirst(l);
}
static List popFirst_ping(int n, List l) {
ping();
return popFirst(n, l);
}
static String sfu(Object o) { return structureForUser(o); }
static boolean checkCondition(Object condition, Object... args) {
return isTrue(callF(condition, args));
}
static boolean checkCondition(IF1 condition, A arg) {
return isTrue(callF(condition, arg));
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null) for (A x : a) l.add(x);
return l;
}
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);
}
static Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static TreeMap litcimap(Object... x) {
return litCIMap(x);
}
static String replaceVars(String s, Map map) {
return empty(map) ? s : join(replaceVars(javaTok(s), map));
}
static List replaceVars(List tok, Map map) {
if (empty(map)) return tok;
tok = cloneList(tok);
for (String var : keys(map))
jreplace(tok, var, map.get(var));
return tok;
}
static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
static boolean isTrueOpt(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
return false;
}
static LinkedList mapToLinkedList(Iterable l, Object f) {
LinkedList x = new LinkedList();
if (l != null) for (Object o : l)
x.add(callF(f, o));
return x;
}
static LinkedList mapToLinkedList(Iterable l, IF1 f) {
return mapToLinkedList(l, (Object) f);
}
static Map mapValues(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map))
m.put(key, callF(func, map.get(key)));
return m;
}
static Map mapValues(Map map, IF1 f) {
return mapValues(f, map);
}
static Map mapValues(Map map, Object func) {
return mapValues(func, map);
}
static String optRound(String s) {
return roundBracketIfMoreThanOneToken(s);
}
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static void pcallFAll(Collection l, Object... args) {
if (l != null) for (Object f : cloneList(l)) pcallF(f, args);
}
static void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static boolean nempty(Collection c) {
return !empty(c);
}
static boolean nempty(CharSequence s) {
return !empty(s);
}
static boolean nempty(Object[] o) { return !empty(o); }
static boolean nempty(byte[] o) { return !empty(o); }
static boolean nempty(int[] o) { return !empty(o); }
static boolean nempty(Map m) {
return !empty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean nempty(Object o) { return !empty(o); }
static Map mapKeys(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map))
m.put(callF(func, key), map.get(key));
return m;
}
static Map mapKeys(Map map, Object func) {
return mapKeys(func, map);
}
static Map mapKeys(Map map, IF1 func) {
return mapKeys(map, (Object) func);
}
static A lookupOrKeep(Map map, A key) {
return map != null && map.containsKey(key) ? map.get(key) : key;
}
static String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder out = new StringBuilder((int) (l(s)*1.5+2));
quote_impl(s, out);
return out.toString();
}
static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static List tok_splitAtAmpersand(String s) {
return splitAtTokens(javaTokWithAllBrackets(s), "&");
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(short[] a) { return a == null ? 0 : a.length; }
static int l(long[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(double[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Iterator i) { return iteratorCount_int_close(i); } // consumes the iterator && closes it if possible
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); }
static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o == null ? 0
: o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: o instanceof Collection ? l((Collection) o)
: o instanceof Object[] ? l((Object[]) o)
: o instanceof boolean[] ? l((boolean[]) o)
: o instanceof byte[] ? l((byte[]) o)
: o instanceof char[] ? l((char[]) o)
: o instanceof short[] ? l((short[]) o)
: o instanceof int[] ? l((int[]) o)
: o instanceof float[] ? l((float[]) o)
: o instanceof double[] ? l((double[]) o)
: o instanceof long[] ? l((long[]) o)
: (Integer) call(o, "size");
}
static int l(IntRange r) { return r == null ? 0 : r.length(); }
static Object first(Object list) {
return first((Iterable) list);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(IterableIterator i) {
return first((Iterator ) i);
}
static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1) return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static String join(Iterable strings) {
return join("", strings);
}
static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
static String[] dropFirst(String[] a) {
return drop(1, a);
}
static Object[] dropFirst(Object[] a) {
return drop(1, a);
}
static List dropFirst(List l) {
return dropFirst(1, l);
}
static List dropFirst(int n, Iterable i) { return dropFirst(n, toList(i)); }
static List dropFirst(Iterable i) { return dropFirst(toList(i)); }
static List dropFirst(int n, List l) {
return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
static List dropFirst(List l, int n) {
return dropFirst(n, l);
}
static String dropFirst(int n, String s) { return substring(s, n); }
static String dropFirst(String s, int n) { return substring(s, n); }
static String dropFirst(String s) { return substring(s, 1); }
static String tok_deRoundOrCurlyBracket(String s) {
return isCurlyBraced(s) || tok_isRoundBracketed(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
}
static Map gazelle_deepZip_keepBrackets(String inputA, String inputB, Object... __) {
Map map = gazelle_zip_keepBrackets(inputA, inputB);
if (map == null) return null;
Map map2 = similarEmptyMap(map);
for (String a : keys( map)) { String b = map.get(a);
if (tok_isRoundOrCurlyBracketed(a) && tok_isRoundOrCurlyBracketed(b)) {
String aa = tok_deRoundOrCurlyBracket(a);
String bb = tok_deRoundOrCurlyBracket(b);
Map subMap = gazelle_deepZip_keepBrackets(aa, bb, __);
if (subMap == null) return null;
if (!putAllStrictlyIC(map2, subMap)) return null;
} else
if (!strictPutIC(map2, a, b)) return null;
}
return map2;
}
static boolean all(Object pred, Collection l) {
if (l != null) for (Object o : l) if (!isTrue(callF(pred, o))) return false;
return true;
}
static boolean all(Iterable l, IF1 f) {
if (l != null) for (A a : l) if (!f.get(a)) return false;
return true;
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static boolean isDollarVar(String s) {
return startsWith(s, '$') && isJavaIdentifierAfter(s, 1);
}
static String replaceCodeTokensUsingMap(String s, Map map) {
return join(replaceCodeTokensUsingMap(javaTok(s), map));
}
static List replaceCodeTokensUsingMap(List tok, Map map) {
List out = emptyList(tok);
for (int i = 0; i < l(tok); i++) {
out.add(odd(i) ? lookupOrKeep(map, tok.get(i)) : tok.get(i));
}
return out;
}
static String replaceCodeTokensUsingMap(Map map, String s) {
return replaceCodeTokensUsingMap(s, map);
}
// TODO: extended multi-line strings
static int javaTok_n, javaTok_elements;
static boolean javaTok_opt = false;
static List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') { // allow multi-line strings, but not for '
++j;
break;
} else if (c2 == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll = false;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions = false;
static Map ping_actions = newWeakHashMap();
static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions ) ping_impl(true /* XXX */);
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized(ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static List map(Iterable l, Object f) { return map(f, l); }
static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null) for (Object o : l)
x.add(callF(f, o));
return x;
}
static List map(Iterable l, F1 f) { return map(f, l); }
static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null) for (A o : l)
x.add(callF(f, o));
return x;
}
static List map(IF1 f, Iterable l) { return map(l, f); }
static List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
x.add(f.get(o));
return x;
}
static List map(IF1 f, A[] l) { return map(l, f); }
static List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
x.add(f.get(o));
return x;
}
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }
static List map(Object f, Map map) {
return map(map, f);
}
// map: func(key, value) -> list element
static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null) for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static String className(Object o) {
return getClassName(o);
}
static void think(String thought) {
miniChat(thought);
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static A pcallF(F0 f) { try {
return f == null ? null : f.get();
} catch (Throwable __e) { return null; } }
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static void pcallF(VF1 f, A a) {
try {
if (f != null) f.get(a);
} catch (Throwable __e) { _handleException(__e); }
}
static Set cloneCISet(Collection l) {
Set set = ciSet();
if (l != null) synchronized(collectionMutex(l)) {
addAll(set, l);
}
return set;
}
static List getAndClearList(Collection l) {
if (l == null) return emptyList();
synchronized(collectionMutex(l)) {
List out = cloneList(l);
l.clear();
return out;
}
}
static List callFAll(Collection l, Object... args) {
return callF_all(l, args);
}
static A pnlWithHeading(String heading, A l) {
printAsciiHeading(heading);
return pnl(l);
}
static boolean eqicOneOf(String s, String... l) {
for (String x : l) if (eqic(s, x)) return true; return false;
}
static String tok_dropRoundBrackets(String s) {
return join(tok_dropRoundBrackets(javaTok(s)));
}
static List tok_dropRoundBrackets(List tok) {
for (int i = 1; i < l(tok); i+= 2) {
while (eqGetOneOf(tok, i, "(", ")")) {
tokAppend(tok, i-1, tok.get(i+1));
removeSubList(tok, i, i+2);
}
}
return tok;
}
static List filter(Iterable c, Object pred) {
if (pred instanceof F1) return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null) for (Object o : c)
if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
static List filter(Object pred, Iterable c) {
return filter(c, pred);
}
static List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null) for (B o : c)
if (pred.get(o))
x.add(o);
return x;
}
static List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
//ifclass IF1
static List filter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null) for (B o : c)
if (pred.get(o))
x.add(o);
return x;
}
static List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
//endif
static Pair pair(A a, B b) {
return new Pair(a, b);
}
static Pair pair(A a) {
return new Pair(a, a);
}
static String withoutLeadingLinesEmptyAfterTrim_autoUnindent(String s) {
return autoUnindent(withoutLeadingLinesEmptyAfterTrim(s));
}
static String tok_deRoundOrCurlyBracket_keepFirstSpacing(String s) {
return isCurlyBraced(s) || tok_isRoundBracketed(s) ? join(dropFirstTwoAndLastThree(javaTok(s))) : s;
}
static > C assertContains(C c, A y) {
return assertContains(null, c, y);
}
static > C assertContains(String msg, C c, A y) {
if (!contains(c, y))
throw fail((msg != null ? msg + ": " : "") + y + " not contained in " + c);
return c;
}
static B firstValue(Map map) {
return first(values(map));
}
static > C assertDoesntContain(C c, A y) {
return assertDoesntContain(null, c, y);
}
static > C assertDoesntContain(String msg, C c, A y) {
if (contains(c, y))
throw fail((msg != null ? msg + ": " : "") + y + " contained in " + c);
return c;
}
static void philosophyBot1_math(PhilosophyBot1 bot) {
bot.addNativePredicate("$x >= $y",
(map) -> cmp(parseBigInt(map.get("$x")), parseBigInt(map.get("$y"))) >= 0);
bot.addNativePredicate("$x <= $y",
(map) -> cmp(parseBigInt(map.get("$x")), parseBigInt(map.get("$y"))) <= 0);
bot.addNativePredicate("$x > $y",
(map) -> cmp(parseBigInt(map.get("$x")), parseBigInt(map.get("$y"))) > 0);
bot.addNativePredicate("$x < $y",
(map) -> cmp(parseBigInt(map.get("$x")), parseBigInt(map.get("$y"))) < 0);
}
static void philosophyBot1_bool(PhilosophyBot1 bot) {
// native predicates now work in rule lhs too
bot.addNativePredicate("true", (map) -> true);
}
static void philosophyBot1_orHandler(PhilosophyBot1 bot) {
bot.logicRulePreprocessors.add(rule -> {
if (!(rule.lhs instanceof String)) return false;
List tok = bot.mainTokenize(tok_deCurlyOrRound((String) rule.lhs));
if (countCodeTokens(tok) == 3 && eq(secondCodeToken(tok), "|")) {
// split into two rules
print("Splitting or: " + tok);
bot.addLogicRule(new PhilosophyBot1.LogicRule(firstCodeToken(tok), rule.rhs));
bot.addLogicRule(new PhilosophyBot1.LogicRule(lastCodeToken(tok), rule.rhs));
return true;
}
return false;
});
}
static void philosophyBot1_iotaHandler(PhilosophyBot1 bot) {
bot.addNativePredicate("iota($x)",
(map) -> iota(parseInt($x(map))));
}
static List tlft_honoringBrackets(String text) {
return trimAll(lines_honoringBrackets(text));
}
static A $x(Map map) {
return mapGet(map, "$x");
}
static boolean eqic(String a, String b) {
if ((a == null) != (b == null)) return false;
if (a == null) return true;
return a.equalsIgnoreCase(b);
}
static boolean eqic(char a, char b) {
if (a == b) return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2) return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static List javaTokWithBrackets(String s) {
return javaTokPlusBrackets(s);
}
static String joinWithSpace(Collection c) {
return join(" ", c);
}
static String joinWithSpace(String... c) {
return join(" ", c);
}
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;
}
static List antiFilter(Object pred, Iterable c) {
return antiFilter(c, pred);
}
static List antiFilter(Object pred, Object[] c) {
return antiFilter(pred, wrapArrayAsList(c));
}
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;
}
static List antiFilter(F1 pred, Iterable c) {
return antiFilter(c, pred);
}
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;
}
static List antiFilter(IF1 pred, Iterable c) {
return antiFilter(c, pred);
}
static List words2_plusApostrophe(String s) {
List l = new ArrayList();
int n = l(s);
for (int i = 0; i < n; ) {
int j = i;
while (j < n && isLetterOrDigitOrApostrophe(s.charAt(j)))
++j;
if (j > i) l.add(substring(s, i, j));
while (j < n && !isLetterOrDigitOrApostrophe(s.charAt(j)))
++j;
i = j;
}
return l;
}
static TreeSet asCISet(Iterable c) {
return toCaseInsensitiveSet(c);
}
static TreeSet asCISet(String... x) {
return toCaseInsensitiveSet(x);
}
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;
}
static Set filterCISet(Object pred, Iterable c) {
return filterCISet(c, pred);
}
static Set filterCISet(Iterable c, IF1 pred) {
return filterCISet(c, (Object) pred);
}
static List listMinusList(Collection l, Collection stuff) {
if (empty(stuff) && l instanceof List) return (List) l;
List l2 = cloneList(l);
for (Object o : stuff)
l2.remove(o);
return l2;
}
static void withCancelPoint(VF1 r) {
CancelPoint cp = newCancelPoint(); try {
try {
callF(r, cp);
} catch (Throwable e) {
e = innerException(e);
if (!(e instanceof CancelToCancelPoint && ((CancelToCancelPoint) e).cp == cp))
rethrow(e);
}
} finally { _close(cp); }}
static void withCancelPoint(IVF1 r) {
CancelPoint cp = newCancelPoint(); try {
try {
r.get(cp);
} catch (Throwable e) {
e = innerException(e);
if (!(e instanceof CancelToCancelPoint && ((CancelToCancelPoint) e).cp == cp))
rethrow(e);
}
} finally { _close(cp); }}
static boolean containsDollarVars(String s) {
List tok = javaTok(s);
for (int i = 1; i < l(tok); i += 2)
if (isDollarVar(tok.get(i))) return true;
return false;
}
static RuntimeException cancelTo(CancelPoint cp) {
if (cp.closed) throw fail("cancel point closed");
throw new CancelToCancelPoint(cp);
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o == null) return null;
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static Object get_raw(Object o, String field) { try {
if (o == null) return null;
Field f = get_findField(o.getClass(), field);
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
makeAccessible(f);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static Object get(String field, Object o) {
return get(o, field);
}
static void add(BitSet bs, int i) {
bs.set(i);
}
static boolean add(Collection c, A a) {
return c != null && c.add(a);
}
static void add(Container c, Component x) {
addToContainer(c, x);
}
static void addPair(Collection> c, A a, B b) {
if (c != null) c.add(pair(a, b));
}
static IntRange intRange_last(List l) {
int n = l(l);
return intRange(n-1, n);
}
static IntRange intRange(int start, int end) {
return new IntRange(start, end);
}
static A popFirst(List l) {
if (empty(l)) return null;
A a = first(l);
l.remove(0);
return a;
}
static A popFirst(Collection l) {
if (empty(l)) return null;
A a = first(l);
l.remove(a);
return a;
}
static List popFirst(int n, List l) {
List part = cloneSubList(l, 0, n);
removeSubList(l, 0, n);
return part;
}
static void addAll(Collection c, Iterable b) {
if (c != null && b != null) for (A a : b) c.add(a);
}
static boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static boolean addAll(Collection c, B... b) {
return c != null && c.addAll(Arrays.asList(b));
}
static Map addAll(Map a, Map extends A,? extends B> b) {
if (a != null) a.putAll(b);
return a;
}
static IterableIterator> outerProduct_pairs(Collection lA, Collection lB) {
return outerProductPairs(lA, lB);
}
static IterableIterator> outerProduct_pairs(Pair extends Collection, ? extends Collection> p) {
return outerProduct_pairs(p.a, p.b);
}
static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static List subList(List l, int startIndex, int endIndex) {
if (l == null) return null;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex >= endIndex) return ll();
if (startIndex == 0 && endIndex == n) return l;
return l.subList(startIndex, endIndex);
}
static List subList(List l, IntRange r) {
return subList(l, r.start, r.end);
}
static int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
static boolean stdEq2(Object a, Object b) {
if (a == null) return b == null;
if (b == null) return false;
if (a.getClass() != b.getClass()) return false;
for (String field : allFields(a))
if (neq(getOpt(a, field), getOpt(b, field)))
return false;
return true;
}
static int stdHash2(Object a) {
if (a == null) return 0;
return stdHash(a, toStringArray(allFields(a)));
}
static Throwable printStackTrace2(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace2(e));
return e;
}
static void printStackTrace2() {
printStackTrace2(new Throwable());
}
static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static String standard_toString(Object o) {
if (o == null) return "null";
String name = shortClassName(o);
Set fields = fieldNames(o);
if (empty(fields)) return name;
return name + "(" + joinWithComma(mapNonNulls(fields, field -> {
Object value = get(o, field);
if (value == null) return null;
return field + "=" + str(value);
})) + ")";
}
static TreeSet ciSet() {
return caseInsensitiveSet();
}
static TreeSet caseInsensitiveSet() {
return caseInsensitiveSet_treeSet();
}
static TreeSet caseInsensitiveSet(Collection c) {
return caseInsensitiveSet_treeSet(c);
}
static TreeSet treeSet() {
return new TreeSet();
}
static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1));
}
static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions )
ping_impl(true);
}
// this syntax should be removed...
static Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static Map> callF_cache = newDangerousWeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static A callF(IF0 f) {
return f == null ? null : f.get();
}
static B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static void callF(VF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Object f, Object... args) { try {
if (f instanceof String)
return callMC((String) f, args);
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1) return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) { throw rethrow(__e); } }
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
makeAccessible(m);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0) return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i+1 < l && s.charAt(i+1) == '\n') ++i;
}
}
return out.toString();
}
static void print_append(Appendable buf, String s, int max) { try {
synchronized(buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) { throw rethrow(__e); } }
static Pair splitAtDoubleArrow_pair(String s) {
return splitAtDoubleArrow_pair(javaTokWithBrackets(s));
}
static Pair splitAtDoubleArrow_pair(List tok) {
return listToPair(splitAtDoubleArrow(tok));
}
static ArrayList emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
// Try to match capacity
static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
// get correct type at once
static ArrayList emptyList(Class c) {
return new ArrayList();
}
static Map emptyMap() {
return new HashMap();
}
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static String getType(Object o) {
return getClassName(o);
}
static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static boolean tok_isRoundBracketed(String s) {
List tok = tok_combineRoundBrackets_keep(javaTok(s));
return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "(", ")");
}
static List dropFirstThreeAndLastThree(List l) {
return dropFirstAndLast(3, l);
}
static int countTokens(String s) {
return l(javaTokC(s));
}
static int countTokens(List tok) {
return l(tok)/2;
}
static boolean isCurlyBraced(String s) {
List tok = tok_combineCurlyBrackets_keep(javaTok(s));
return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}");
}
static String tok_unCurlyBracket_keepSpaces(String s) {
return isCurlyBraced(s) ? join(dropFirstTwoAndLastTwo(javaTok(s))) : s;
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static String repeat(char c, int n) {
n = Math.max(n, 0);
char[] chars = new char[n];
for (int i = 0; i < n; i++)
chars[i] = c;
return new String(chars);
}
static List repeat(A a, int n) {
n = Math.max(n, 0);
List l = new ArrayList(n);
for (int i = 0; i < n; i++)
l.add(a);
return l;
}
static List repeat(int n, A a) {
return repeat(a, n);
}
static int indent_default = 2;
static String indent(int indent) {
return repeat(' ', indent);
}
static String indent(int indent, String s) {
return indent(repeat(' ', indent), s);
}
static String indent(String indent, String s) {
return indent + s.replace("\n", "\n" + indent);
}
static String indent(String s) {
return indent(indent_default, s);
}
static List indent(String indent, List lines) {
List l = new ArrayList();
if (lines != null) for (String s : lines)
l.add(indent + s);
return l;
}
static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static Throwable innerException(Throwable e) {
return getInnerException(e);
}
static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static ArrayList cloneList(Collection l) {
if (l == null) return new ArrayList();
synchronized(collectionMutex(l)) {
return new ArrayList (l);
}
}
static LinkedList asLinkedList(Iterable s) {
if (s instanceof LinkedList) return ((LinkedList) s);
LinkedList l = new LinkedList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static Object collectionMutex(List l) {
return l;
}
static Object collectionMutex(Object o) {
if (o instanceof List) return o;
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
static String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
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);
}
static Iterator emptyIterator() {
return Collections.emptyIterator();
}
static TreeMap litCIMap(Object... x) {
TreeMap map = caseInsensitiveMap();
litmap_impl(map, x);
return map;
}
static String jreplace(String s, String in, String out) {
return jreplace(s, in, out, null);
}
static String jreplace(String s, String in, String out, Object condition) {
List tok = javaTok(s);
return jreplace(tok, in, out, condition) ? join(tok) : s;
}
// leaves tok properly tokenized
// returns true iff anything was replaced
static boolean jreplace(List tok, String in, String out) {
return jreplace(tok, in, out, false, true, null);
}
static boolean jreplace(List