Warning : session_start(): open(/var/lib/php/sessions/sess_2ka1rkd8o2nth1he7qo76cf6b5, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import java.text.NumberFormat;
class main {
static 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 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)); }
int n; // when added
public String toString() {
return (n == 0 ? "" : "[" + n + "] ") + lhs + " => " + 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 shortClassName(this) + "(" + 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 shortClassName(this) + "(" + 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 shortClassName(this) + "(" + 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 shortClassName(this) + "(" + 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 shortClassName(this) + "(" + 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 shortClassName(this) + "(" + 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 shortClassName(this) + "(" + 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 boolean programLoaded = false;
transient int maxRounds = 1000;
transient int maxFacts = 1000;
transient Set facts = linkedCISet();
transient Set originalFacts = ciSet();
transient LinkedHashSet logicRules = new LinkedHashSet(); // modified with sync
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 boolean verbose = true;
transient List onProcedureEnded = new ArrayList();
transient List> onLogicRuleAdded = new ArrayList();
transient List> onFactAdded = new ArrayList();
transient boolean printNonMatches, debugContradictionChecks;
transient boolean standardImportsLoaded = false;
transient boolean curryAllRules = true; // rewrite "a & b => c" to a => b => c
transient int logicRulesCounter;
transient boolean thoughtBegun = false;
transient boolean printFactsAfterThinking = true;
// 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");
// phrase replacements that are made in every fact.
// functionality is enabled by philosophyBot1_addDeepReplacement
transient Map deepReplacements;
transient List> deepTransformers;
Map extensions;
PhilosophyBot1() {
// find contradictions
anyCodeOnFacts.newA(fact -> {
Boolean b = checkNativeCondition(fact);
if (debugContradictionChecks)
print("Fact check: " + b + " - " + fact);
if (isFalse(b))
addFact("contradiction");
});
_standardHandlers();
}
PhilosophyBot1(String program) { this();
this.program = program; }
void addRule(String s) {
Pair p = splitAtFirstDoubleArrow(javaTokWithBrackets(s));
if (p == null) if (verbose) print("addRule failed: " + s);
addLogicRule(new LogicRule(splitAtAmpersand2(p.a), p.b));
}
void addRules(Iterable l) {
for (String s : unnull(l)) addRule(s);
}
Object splitRuleRHS(Object rhs) {
if (rhs instanceof String) {
Pair p = splitAtFirstDoubleArrow(javaTokWithBrackets(((String) rhs)));
if (p != null) return splitRuleRHS(new LogicRule(splitAtAmpersand2(p.a), splitRuleRHS(p.b)));
return splitAtAmpersand2(((String) rhs));
}
return rhs;
}
LogicRule curryLHS(LogicRule rule) {
while (licensed()) {
Object lhs = rule.lhs;
if (lhs instanceof And) {
Object a = ((And) lhs).a;
Object b = ((And) lhs).b; rule = new LogicRule(a, new LogicRule(b, rule.rhs)); }
else break;
}
return rule;
}
void addLogicRule(LogicRule rule) {
rule.rhs = splitRuleRHS(rule.rhs);
if (curryAllRules)
rule = curryLHS(rule);
for (IF1 p : logicRulePreprocessors)
if (p.get(rule)) return; // has been preprocessed
rule.n = ++logicRulesCounter;
// 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))
addRewrittenRHS(rule.rhs);
if (syncAdd(logicRules, rule)) {
if (verbose) print("Got logic rule", rule);
pcallFAll(onLogicRuleAdded, 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) {
ping();
fact = trim(fact);
if (empty(fact)) return;
if (l(facts) >= maxFacts) 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))) {
if (verbose) print("Got procedure:");
if (verbose) 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)) {
if (verbose) print("Got fact: " + fact);
pcallFAll(onFactAdded, fact);
rulesOnFacts.newB(fact); // to combine it with the rules
codeOnFacts.newB(fact);
anyCodeOnFacts.newB(fact);
}
}
void addRewrittenRHS(Object o) {
if (o instanceof LogicRule)
addLogicRule(((LogicRule) o));
else if (o instanceof And) {
Object a = ((And) o).a;
Object b = ((And) o).b;
addRewrittenRHS(a);
addRewrittenRHS(b);
} else if (o != null)
addFact((String) o);
}
void addFactFromProgram(String fact) {
if (countJavaTokens(fact) == 0) return;
fact = javaDropAllComments(fact);
originalFacts.add(fact);
addFact(fact);
}
void runProcedure(String proc) { try {
if (verbose) 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)) {
if (verbose) 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)));
if (verbose) 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 __5= result; if (__5 != null) return __5; }
} 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 replaceCodeTokensUsingMap(((String) o), map);
return null;
}
String format(String s, Map map) {
return replaceCodeTokensUsingMap(s, mapValues("optRound",map));
}
// if f returns null, go through structure
Object transform(IF1 f, Object o) {
if (o == null) return null;
ping();
{ Object __6= f.get(o); if (__6 != null) return __6; }
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!
if (verbose) 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);
if (verbose) print("rhs_replaced", rhs_replaced);
if (remaining == null) {
// Add as fact / new rule
addRewrittenRHS(rhs_replaced);
} else {
// Apply mapping to remaining condition
Object remaining_replaced = replaceVars(remaining, map);
addLogicRule(new LogicRule(remaining_replaced, rhs_replaced));
}
}
public void run() { 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))
addFactFromProgram(s);
// find logic rules
List paragraphs4 = new ArrayList();
for (String para : paragraphs3) {
Pair p = splitAtFirstDoubleArrow(javaTokWithBrackets(para));
if (p == null) { paragraphs4.add(para); continue; }
addLogicRule(new LogicRule(splitAtAmpersand2(p.a), p.b));
}
if (smartParser1_verbose) pnlStruct("Unparsed - assuming facts", paragraphs4);
// assume the unparsed stuff consists of facts
for (String para : paragraphs4)
addFactFromProgram(para);
}
void parseProgram() {
if (programLoaded) return;
programLoaded = true;
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() {
parseProgram();
thoughtBegun = true;
int round = 0;
while (round++ < maxRounds) { ping();
long lastSize = size();
if (verbose) print("Logic round " + round + ", size: " + lastSize);
while (doSomeLogic() && round++ < maxRounds && l(facts) < maxFacts) {}
for (List proc : getAndClearList(proceduresToRun))
{ ping(); runParsedProcedure(proc); }
callFAll(extraLogicOperations);
if (size() == lastSize) {
if (verbose) print("No changes, exiting");
break;
}
}
// We're done logicking, so print all the facts gathered
Collection madeFacts = factsDeduced();
if (printFactsAfterThinking)
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)));
}
pnlWithHeadingIfNempty("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) {
for (Map map : matchFacts_keepBrackets("theory $x $y"))
if (eqic(properUnquote(tok_deRoundBracket($x(map))), name))
{ openTheory(name, $y(map)); return; }
throw fail("Theory not defined: " + quote(name));
}
void openTheory(String name, String body) {
//print("Raw theory: " + quote(s));
loadProgram(withoutLeadingLinesEmptyAfterTrim_autoUnindent(tok_deRoundOrCurlyBracket_keepFirstSpacing(body)));
if (verbose) 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 -> printIf(verbose, "tlft output",
tlft_honoringBrackets($x(map)))));
addNativePredicate("printNonMatches", () -> { printNonMatches = true; return true; });
philosophyBot1_enableAddSimplifier(this);
}
void addFactPreprocessor(IF1 f) {
factPreprocessors.add(f);
}
void addLogicRulePreprocessor(IF1 f) {
logicRulePreprocessors.add(f);
}
void registerImport(String name, Runnable handler) {
String line = "import " + name;
factPreprocessors.add(s -> {
if (eqic(s, line)) {
if (verbose) 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;
}
void _standardHandlers() {
philosophyBot_autoOpenTheoriesHandler(this);
addFactPreprocessor(s -> { if (eqic(s, "standard imports")) { standardImports(); return true; } return false; });
}
void runAndCheckExpectations() {
run();
checkExpectations();
}
void addDeepTransformer(IF1 transformer) {
if (deepTransformers == null) {
deepTransformers = new ArrayList();
// enable transformers
anyCodeOnFacts.newA(fact ->
addFact(gazelle_deepTransform(
s -> firstTransformersResult(deepTransformers, s), fact)));
}
deepTransformers.add(transformer);
}
Object getExtension(Object key) { return mapGet(extensions, key); }
void addExtension(Object key, Object value) {
if (extensions == null) extensions = new HashMap();
extensions.put(key, value);
}
}
static boolean allLinesAreUnindented(String text) {
for (String s : lines(text))
if (startsWithSpace(s))
return false;
return true;
}
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 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 String stdToString(Object o) {
return standard_toString(o);
}
static Set linkedCISet() {
return new LinkedTreeSet(ciSet());
}
static TreeSet ciSet() {
return caseInsensitiveSet();
}
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 splitAtFirstDoubleArrow(String s) {
return splitAtFirstDoubleArrow(javaTok(s));
}
static Pair splitAtFirstDoubleArrow(List tok) {
int i = indexOfSubList(tok, splitAtDoubleArrow_tok());
return i < 0 ? null : pair(trimJoin(subList(tok, 0, i)), trimJoin(subList(tok, i+3)));
}
static List javaTokWithBrackets(String s) {
return javaTokPlusBrackets(s);
}
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 volatile boolean licensed_yes = true;
static boolean licensed() {
if (!licensed_yes) return false;
ping_okInCleanUp();
return true;
}
static void licensed_off() {
licensed_yes = false;
}
static 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 boolean syncAdd(Collection c, A b) {
if (c == null) return false;
synchronized(c) { return c.add(b); }
}
static void syncAdd(List l, int idx, A b) {
if (l != null) synchronized(l) { l.add(idx, b); }
}
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);
}
//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 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(double[] a) { return a == null || a.length == 0; }
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 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 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 int countJavaTokens(String s) {
return countTokens(s);
}
static int countJavaTokens(List tok) {
return countTokens(tok);
}
static String javaDropAllComments(String s) {
return join(javaDropAllComments(javaTok(s)));
}
static List javaDropAllComments(List tok) {
for (int i = 0; i < l(tok); i += 2)
tok.set(i, tok_javaDropCommentsFromWhitespace(tok.get(i)));
return tok;
}
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 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 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 boolean contains(Producer p, A a) {
if (p != null && a != null) while (true) {
A x = p.next();
if (x == null) break;
if (eq(x, a)) return true;
}
return false;
}
static String withoutLinesEmptyAfterTrim(String text) {
List lines = filter(lines(text), s -> !emptyAfterTrim(s));
return lines_possiblyRTrim(text, lines);
}
// leaves lines enclosed in brackets alone
static String autoUnindent_honoringBrackets(String s) {
List l = lines_honoringBrackets(s);
if (empty(l)) return s;
// find indent
int n = Integer.MAX_VALUE;
for (String line : l)
n = min(n, getIndentOfLine(line));
if (n == 0) return s;
// unindent
int _n = n;
return lines_possiblyRTrim(s, map(l, line -> substring(line, _n)));
}
/* e.g.
if (x exists):
ask (what is x?)
else:
ask (does x exist?)
=> a list with two elements
input has to be starting at column 1! (call autoUnindent if unsure)
*/
static List groupPythonStyleIndents_honoringBrackets(String text) {
List lines = lines_honoringBrackets(text);
List out = new ArrayList();
int startOfBlock = 0;
for (int i = 0; i < l(lines); i++) {
boolean indented = startsWithSpace(lines.get(i));
if (!indented) {
addIfNempty(out, lines_rtrim(subList(lines, startOfBlock, i)));
startOfBlock = i;
}
}
addIfNempty(out, lines_rtrim(subList(lines, startOfBlock)));
return out;
}
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 String firstCodeToken(String s) {
return firstJavaToken(s);
}
static String firstCodeToken(List tok) {
return get(tok, 1);
}
static A assertEquals(Object x, A y) {
return assertEquals(null, x, y);
}
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;
}
static String deRoundBracket(String s) {
if (startsWith(s, "(") && endsWith(s, ")"))
return substring(s, 1, l(s)-1);
return s;
}
static String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
static String joinSubList(List l, int i) {
return join(subList(l, i));
}
static String joinSubList(List l, IntRange r) {
return r == null ? null : joinSubList(l, r.start, r.end);
}
static String secondCodeToken(List tok) {
return get(tok, 3);
}
static A last(List l) {
return empty(l) ? null : l.get(l.size()-1);
}
static char last(String s) {
return empty(s) ? '#' : s.charAt(l(s)-1);
}
static int last(int[] a) {
return l(a) != 0 ? a[l(a)-1] : 0;
}
static double last(double[] a) {
return l(a) != 0 ? a[l(a)-1] : 0;
}
static A last(A[] a) {
return l(a) != 0 ? a[l(a)-1] : null;
}
static A last(Iterator it) {
A a = null;
while (it.hasNext()) { ping(); a = it.next(); }
return a;
}
static A last(Collection l) {
if (l == null) return null;
Iterator it = iterator(l);
A a = null;
while (it.hasNext()) { ping(); a = it.next(); }
return a;
}
static A last(SortedSet l) {
return l == null ? null : l.last();
}
static int indexOf(List l, A a, int startIndex) {
if (l == null) return -1;
int n = l(l);
for (int i = startIndex; i < n; i++)
if (eq(l.get(i), a))
return i;
return -1;
}
static int indexOf(List l, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
static int indexOf(List l, A a) {
if (l == null) return -1;
return l.indexOf(a);
}
static int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, char b) {
return a == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, int i, char b) {
return indexOf(a, b, i);
}
static int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(A[] x, A a) {
int n = l(x);
for (int i = 0; i < n; i++)
if (eq(x[i], a))
return i;
return -1;
}
static void assertTrue(Object o) {
if (!(eq(o, true) /*|| isTrue(pcallF(o))*/))
throw fail(str(o));
}
static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
// TODO: extended multi-line strings
static int javaTok_n, javaTok_elements;
static boolean javaTok_opt = false;
static List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') { // allow multi-line strings, but not for '
++j;
break;
} else if (c2 == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
static String assertIdentifier(String s) {
return assertIsIdentifier(s);
}
static String assertIdentifier(String msg, String s) {
return assertIsIdentifier(msg, s);
}
static String trimJoinSubList(List l, int i, int j) {
return trim(join(subList(l, i, j)));
}
static String trimJoinSubList(List l, int i) {
return trim(join(subList(l, i)));
}
static A pnl(String prefix, A l) {
printNumberedLines(prefix, l);
return l;
}
static A pnl(A l) {
printNumberedLines(l);
return l;
}
static A pnl(A map) {
printNumberedLines(map);
return map;
}
static A[] pnl(A[] a) {
printNumberedLines(a);
return a;
}
static String pnl(String s) {
printNumberedLines(lines(s));
return s;
}
static List tok_splitAtAmpersand(String s) {
return splitAtTokens(javaTokWithAllBrackets(s), "&");
}
static Object first(Object list) {
return first((Iterable) list);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(IterableIterator i) {
return first((Iterator ) i);
}
static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
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);
}
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 String withoutLeadingLinesEmptyAfterTrim_autoUnindent(String s) {
return autoUnindent(withoutLeadingLinesEmptyAfterTrim(s));
}
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;
}
// rtrims each item
static List tok_splitAtEmptyLines(String s) {
List indices = new ArrayList();
List tok = javaTokWithAllBrackets(s);
List out = new ArrayList();
int start = 0;
String spacing = "";
for (int i = 2; i+1 < l(tok); i += 2) {
int idx = indexOf_regexp(tok.get(i), "\r?\n\\s*\r?\n");
if (idx < 0) continue;
int idx2 = idx+1;
if (tok.get(i).charAt(idx) == '\r') ++idx2;
out.add(dropPrefix("\n", spacing + joinSubList(tok, start, i)));
start = i+1;
spacing = substring(tok.get(i), idx2); // TODO: not exact
}
if (start < l(tok))
out.add(dropPrefix("\n", spacing + joinSubList(tok, start)));
return out;
}
static String n2(long l) { return formatWithThousands(l); }
static String n2(Collection l) { return n2(l(l)); }
static String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
static String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
static String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static String n2(Map m, String singular) {
return n2(l(m), singular);
}
static String n2(Object[] a, String singular) { return n2(l(a), singular); }
static String n2(Object[] a, String singular, String plural) { return n_fancy2(a, singular, plural); }
static String joinWithEmptyLines(Iterable l) {
return join("\n\n", map("rtrim",l));
}
static String joinWithEmptyLines(String... l) {
return joinWithEmptyLines(asList(l));
}
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 boolean isSingleLine(String s) {
return !containsNewLine(s);
}
// supports the usual quotings (", variable length double brackets) except ' quoting
static boolean isQuoted(String s) {
if (isNormalQuoted(s)) return true; // use the exact version
return isMultilineQuoted(s);
}
static boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
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;
}
static Pair, List> filterAntiFilter(Iterable c, Object pred) {
List yes = new ArrayList();
List no = new ArrayList();
if (c != null) for (A o : c)
(isTrue(callF(pred, o)) ? yes : no).add(o);
return pair(yes, no);
}
static Pair, List> filterAntiFilter(Iterable c, IF1 pred) {
return filterAntiFilter(c, (Object) pred);
}
static Pair, List> filterAntiFilter(IF1 pred, Iterable c) {
return filterAntiFilter(c, pred);
}
static Pair, List> filterAntiFilter(Object pred, Iterable c) {
return filterAntiFilter(c, pred);
}
static List tlft(String s) { return toLinesFullTrim(s); }
static List tlft(File f) { return toLinesFullTrim(f); }
// currently collection and map only
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));
}
static > B pnlStruct(B l) {
pnlStruct((Iterable ) l);
return l;
}
static Iterable pnlStruct(Iterable l) {
return pnlStruct("", l);
}
static Iterable pnlStruct(String prefix, Iterable l) {
int i = 0;
if (l != null) for (A a : l) print(prefix + (++i) + ". " + struct_noStringSharing(a));
return l;
}
static A[] pnlStruct(A[] l) {
pnlStruct(asList(l));
return l;
}
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;
}
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 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 A pnlWithHeadingIfNempty(String heading, A l) {
if (nempty(l)) pnlWithHeading(heading, l);
return l;
}
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(B[] 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 properUnquote(String s) {
return isProperlyQuoted(s) ? unquote(s) : s;
}
static A $x(Map map) {
return mapGet(map, "$x");
}
static A $y(Map map) {
return mapGet(map, "$y");
}
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);
bot.addNativePredicate("$x = $y",
map -> eqic($x(map), $y(map)));
bot.addNativePredicate("$x != $y",
map -> {
String x = $x(map), y = $y(map);
print("equality check: " + x + " / " + y);
return !eqic(x, y);
});
}
static void philosophyBot1_orHandler(PhilosophyBot1 bot) {
bot.addLogicRulePreprocessor(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 A printIf(boolean b, A a) {
if (b) print(a);
return a;
}
static A printIf(boolean b, String s, A a) {
if (b) print(s, a);
return a;
}
static List tlft_honoringBrackets(String text) {
return trimAll(lines_honoringBrackets(text));
}
static void philosophyBot1_enableAddSimplifier(PhilosophyBot1 bot) {
bot.addFactPreprocessor(fact -> {
String rule = $x(bot.matchString("add simplifier $x", fact));
if (rule == null) return false;
print("adding simplifier: " + rule);
Pair p = tok_splitAtDoubleArrow_pair(rule);
if (p == null) return false;
philosophyBot1_addSimplificationRule(bot, p.a, p.b);
return true;
});
}
static String joinWithSpace(Collection c) {
return join(" ", c);
}
static String joinWithSpace(String... c) {
return join(" ", c);
}
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);
}
// example use:
// auto open theories
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 run(String progID, String... args) {
Class main = hotwire(progID);
callMain(main, args);
return main;
}
// transformer can return null or input on no change
// will not call transformer on individual words
static String gazelle_deepTransform(IF1 transformer, String input, Object... __) {
if (transformer == null) return input;
// call transformer on whole input, return if change
String transformed = transformer.get(input);
if (transformed != null && transformed != input) return transformed;
// transformer didn't do anything, tokenize & go through parts
Object tokenizer = optPar("tokenizer",__, "javaTokWithBrackets");
List tok = callTokenizer(tokenizer, input);
boolean changes = false;
for (int i = 1; i < l(tok); i += 2) { ping();
String t = tok.get(i);
if (tok_isRoundOrCurlyBracketed(t)) {
String unBracketed = tok_deRoundOrCurlyBracket(t);
transformed = gazelle_deepTransform(transformer, unBracketed, __);
if (transformed != unBracketed) {
if (!changes) tok = cloneList(tok); // in case a caching tokenizer was used
// enclose in brackets & replace
tok.set(i, startsWith(t, "(") ? roundOpt(transformed) : curlyOpt(transformed));
changes = true;
}
}
}
return changes ? join(tok) : input;
}
static A firstTransformersResult(List> transformers, A a) {
for (IF1 f : unnull(transformers))
if (f != null) {
A b = f.get(a);
if (b != null && b != a)
return b;
}
return a;
}
static B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
static B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
static AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
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 lines(Iterable lines) { return fromLines(lines); }
static String lines(Object[] lines) { return fromLines(asList(lines)); }
static List lines(String s) { return toLines(s); }
static boolean startsWithSpace(String s) {
return nempty(s) && isSpace(first(s));
}
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 String standard_toString(Object o) {
if (o == null) return "null";
String name = shortClassName(o);
Set