Warning : session_start(): open(/var/lib/php/sessions/sess_uo66p2725mgvp22fpltq2pdhlm, 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 java.util.function.*;
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 java.awt.geom.*;
import javax.imageio.*;
import java.math.*;
import java.time.Duration;
import java.lang.invoke.VarHandle;
import java.lang.invoke.MethodHandles;
// See: #1024878
import java.text.NumberFormat;
import java.awt.geom.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import static x30_pkg.x30_util.DynamicObject;
import java.nio.file.Path;
import java.text.*;
import java.nio.charset.Charset;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
class main {
static void allTests_structure() {
test_structure_lambdasAndAnonymousClasses();
test_structure_customObjects();
test_structure_synchroList();
test_restructure_syncLinkedList();
test_structure_synchroLinkedHashMap();
test_structure_synchronizedTreeMap();
test_restructure_MRUCache();
test_restructure_syncMRUCache();
test_restructure_MRUAndAllTimeTop();
test_structure_listContainingItself();
test_unstructureMissingClassToBaseClass();
test_unstructureMissingConcept();
test_structure_multiDimensionalIntArrays();
test_structure_stringArrays();
test_structure_nonTransientPersistenceInfo();
test_structure_transientPersistenceInfo();
test_structure_nonTransientPersistenceInfoInFieldValues();
test_structure_OptimizedMultiSet();
test_structure_innerSubclassOfDynamicObject();
test_structure_IPersistenceInfo();
test_structure_enum();
test_structure_shouldIncludeField();
test_structure_skipDefaultValues();
test_structure_customSerializer();
test_structure_TransientObject();
test_structure_Color();
test_unstructureErrorInConstructor();
test_unstructure_jdkObject();
test_structure_shortArrays();
test_structure_longArrays();
test_structure_doubleArrays();
test_structure_floatArrays();
test_structure_fileAsKey();
test_restructure_CompactHashMap();
test_restructure_CompactHashSet();
test_structure_floatingPoint();
test_unstructureMissingClassObject();
test_unstructure_doneLoading();
print();
print("(Please ignore any possible errors printed above, they are necessary and good.)");
print();
print("All structure + unstructure tests OK!");
print();
}
// We can't deserialize lambdas so we just save them as null
static void test_structure_lambdasAndAnonymousClasses() {
IF0 lambda = () -> 0;
structure_Data d = new structure_Data() {
structure_ClassInfo newClass(Class c) {
structure_ClassInfo info = super.newClass(c);
print(c + " => " + info.nullInstances);
return info;
}
};
assertEqualsVerbose("null", struct(lambda, d));
Runnable anon = new Runnable() { public void run() { try { ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return ""; }};
assertEqualsVerbose("null", struct(anon));
}
static class test_structure_customObjects_A { String a; public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); } }
static class test_structure_customObjects_B extends test_structure_customObjects_A { String b; public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); } }
static void test_structure_customObjects() {
testStructureFunction(nu(test_structure_customObjects_A.class, "a" , "AAA"));
testStructureFunction(nu(test_structure_customObjects_B.class, "a" , "ABC", "b" , "DEF"));
print("OK");
}
static void test_structure_synchroList() {
List l = synchroList();
testStructureFunction(l);
assertEqualsVerbose(_getClass(l), _getClass(restruct(l))); // make sure it's a RandomAccessList
print("OK");
}
static void test_restructure_syncLinkedList() {
List orig = synchronizedList(litlinkedlist("a", "b"));
print(structure(orig));
List ll = (List) (restructure(orig));
assertEquals(orig.getClass(), ll.getClass());
assertTrueVerbose(unwrapSynchronizedList(ll) instanceof LinkedList);
assertEqualsVerbose(orig, ll);
// legacy format
List l2 = (List) (unstructure("syncLL[1, 2]"));
assertEquals(synchronizedList(litlinkedlist()).getClass(), l2.getClass());
assertTrue(unwrapSynchronizedList(l2) instanceof LinkedList);
assertEquals(ll(1, 2), l2);
}
static void test_structure_synchroLinkedHashMap() {
Map m = synchroLinkedHashMap();
m.put("a", "b");
testStructureFunction(m);
assertTrue(unwrapSynchronizedMap(restruct(m)) instanceof LinkedHashMap);
print("OK");
}
static void test_structure_synchronizedTreeMap() {
Map map = synchronizedTreeMap();
String name = className(map);
print(name);
String s;
print(s = struct(map));
Map map2 = (Map) (unstruct(s));
assertEquals(name, className(map2));
assertEquals(map, map2);
map.put("c", "d");
map.put("a", "b");
map.put("d", "e");
map.put("e", "f");
print(s = struct(map));
map2 = (Map) unstruct(s);
assertEquals(name, className(map2));
assertEquals(map, map2);
print("OK");
}
static void test_restructure_MRUCache() {
MRUCache o = new MRUCache();
o.maxSize = 5;
o.put("a", true);
print(structure(o));
MRUCache o2 = (MRUCache) (restructure(o));
assertEqualsVerbose(ll(pair("a", true)), mapToPairs(o2));
assertEqualsVerbose(5, o2.maxSize);
}
static void test_restructure_syncMRUCache() {
MRUCache o = new MRUCache();
o.maxSize = 5;
o.put("a", true);
print(structure(synchronizedMap(o)));
Map o2 = (Map) (restructure(o));
assertEqualsVerbose(ll(pair("a", true)), mapToPairs(o2));
assertEqualsVerbose(5, ((MRUCache) unwrapSynchronizedMap(o2)).maxSize);
}
static void test_restructure_MRUAndAllTimeTop() {
String s = structure(new MRUAndAllTimeTop_optimized());
print(s);
MRUAndAllTimeTop_optimized m = (MRUAndAllTimeTop_optimized) (unstructure(s));
assertEqualsVerbose(s, structure(m));
}
static void test_structure_listContainingItself() {
List l = new ArrayList();
l.add(l);
String s = struct(l);
print(shorten(s, 500));
List l2 = unstructureList(s);
assertEquals(1, l(l2));
assertSame(l2, first(l2));
}
static class test_unstructureMissingClassToBaseClass_Blu extends Concept { test_unstructureMissingClassToBaseClass_Blu ref; }
static class test_unstructureMissingClassToBaseClass_Bla extends test_unstructureMissingClassToBaseClass_Blu {}
static class test_unstructureMissingClassToBaseClass_Blo extends test_unstructureMissingClassToBaseClass_Bla {} // twice derived
// make sure best base class is used
static void test_unstructureMissingClassToBaseClass() {
IF1 classFinder = name -> {
if (eqOneOf(name, className(test_unstructureMissingClassToBaseClass_Bla.class), className(test_unstructureMissingClassToBaseClass_Blo.class))) return null;
return (Class) callF(_defaultClassFinder(), name);
};
for (Class extends test_unstructureMissingClassToBaseClass_Bla> c : ll(test_unstructureMissingClassToBaseClass_Bla.class, test_unstructureMissingClassToBaseClass_Blo.class)) {
structure_Data data = new structure_Data();
data.storeBaseClasses = true;
test_unstructureMissingClassToBaseClass_Bla b = unlisted(c);
b.ref = b;
String struct = structure(b, data);
print("struct", struct);
Object o = unstructure(struct, classFinder);
assertEqualsVerbose(test_unstructureMissingClassToBaseClass_Blu.class, _getClass(o));
assertSameVerbose(o, ((test_unstructureMissingClassToBaseClass_Blu) o).ref);
}
}
static class Blu extends Concept { Blu ref; }
static void test_unstructureMissingConcept() {
Blu b = unlisted(Blu.class);
b.ref = b;
structure_Data data = new structure_Data();
data.storeBaseClasses = true; // try with this new feature
String struct = structure(b, data);
print("struct", struct);
Object o = unstructure(struct, true);
assertEqualsVerbose(Concept.class, _getClass(o));
assertSameVerbose(o, cget(o, "ref"));
}
static void test_structure_multiDimensionalIntArrays() {
int[] a = { 3, 10, -5 };
assertEqualsVerbose("intarray{3, 10, -5}", struct(a));
assertEqualsVerbose(ll(3, 10, -5), toList(restruct(a)));
int[] b = { 4 };
int[][] c = { a, b };
assertEqualsVerbose("intarray/2{intarray{3, 10, -5}, intarray{4}}", struct(c));
int[][] c2 = restruct(c); // check the actual type
assertEqualsVerbose(ll(ll(3, 10, -5), ll(4)), lmap(__17 -> toList(__17), toList(c2)));
// test 3rd dimension
int[][][] d = { c };
assertEqualsVerbose("intarray/3{intarray/2{intarray{3, 10, -5}, intarray{4}}}", struct(d));
int[][][] d2 = restruct(d); // check the actual type
assertEqualsVerbose(ll(ll(ll(3, 10, -5), ll(4))),
lmap(l -> lmap(__18 -> toList(__18), l), d2));
}
static void test_structure_stringArrays() {
String[] a = { "hello", "world", null };
assertEqualsVerbose("array S{\"hello\", \"world\", null}", struct(a));
String[] a2 = restruct(a);
assertEqualsVerbose(toList(a), toList(a2));
String[][] b = { a };
assertEqualsVerbose("array S/2{array S{\"hello\", \"world\", null}}", struct(b));
String[][] b2 = restruct(b);
assertEqualsVerbose(lmap(__19 -> toList(__19), b), lmap(__20 -> toList(__20), b2));
}
static class test_structure_nonTransientPersistenceInfo_Blubb {
String a = "aa", b = "bb";
Map _persistenceInfo;
}
static void test_structure_nonTransientPersistenceInfo() {
assertEqualsVerbose("test_structure_nonTransientPersistenceInfo_Blubb(_persistenceInfo=hm{\"a\"=f}, b=\"bb\")", structure(nu(test_structure_nonTransientPersistenceInfo_Blubb.class, "_persistenceInfo" , litmap("a", false))));
assertEqualsVerbose("test_structure_nonTransientPersistenceInfo_Blubb(a=\"aa\", b=\"bb\")", structure(nu(test_structure_nonTransientPersistenceInfo_Blubb.class, "_persistenceInfo" , null)));
assertEqualsVerbose("test_structure_nonTransientPersistenceInfo_Blubb(_persistenceInfo=hm{\"a\"=t}, a=\"aa\", b=\"bb\")", structure(nu(test_structure_nonTransientPersistenceInfo_Blubb.class, "_persistenceInfo" , litmap("a", true))));
}
static class test_structure_transientPersistenceInfo_Blubb {
String a = "aa", b = "bb";
transient Map _persistenceInfo = litmap("a", false);
}
static void test_structure_transientPersistenceInfo() {
assertEqualsVerbose("test_structure_transientPersistenceInfo_Blubb(b=\"bb\")", structure(new test_structure_transientPersistenceInfo_Blubb()));
assertEqualsVerbose("test_structure_transientPersistenceInfo_Blubb(a=\"aa\", b=\"bb\")", structure(nu(test_structure_transientPersistenceInfo_Blubb.class, "_persistenceInfo" , null)));
assertEqualsVerbose("test_structure_transientPersistenceInfo_Blubb(a=\"aa\", b=\"bb\")", structure(nu(test_structure_transientPersistenceInfo_Blubb.class, "_persistenceInfo" , litmap("a", true))));
}
static class test_structure_nonTransientPersistenceInfoInFieldValues_Blubb extends DynamicObject {
String a = "aa", b = "bb";
}
static void test_structure_nonTransientPersistenceInfoInFieldValues() {
assertEqualsVerbose("test_structure_nonTransientPersistenceInfoInFieldValues_Blubb(b=\"bb\", _persistenceInfo=hm{\"a\"=f})", structure(nuDyn(test_structure_nonTransientPersistenceInfoInFieldValues_Blubb.class, "_persistenceInfo" , litmap("a", false))));
assertEqualsVerbose("test_structure_nonTransientPersistenceInfoInFieldValues_Blubb(a=\"aa\", b=\"bb\")", structure(nuDyn(test_structure_nonTransientPersistenceInfoInFieldValues_Blubb.class, "_persistenceInfo" , null)));
assertEqualsVerbose("test_structure_nonTransientPersistenceInfoInFieldValues_Blubb(a=\"aa\", b=\"bb\", _persistenceInfo=hm{\"a\"=t})", structure(nuDyn(test_structure_nonTransientPersistenceInfoInFieldValues_Blubb.class, "_persistenceInfo" , litmap("a", true))));
}
static void test_structure_OptimizedMultiSet() {
OptimizedMultiSet set = new OptimizedMultiSet();
set.add("a");
set = restructureVerbose(set);
assertEquals(set.getMostPopularEntry(), "a");
assertEquals(1, set.get("a"));
assertEquals(1, set.size());
}
static class XXOuter {
static class SubclassOfDynamicObject extends DynamicObject {
}
}
static void test_structure_innerSubclassOfDynamicObject() {
assertEqualsVerbose("XXOuter$SubclassOfDynamicObject",
structure(new XXOuter.SubclassOfDynamicObject()));
}
static class test_structure_IPersistenceInfo_Blubb implements IPersistenceInfo {
String a = "aa", b = "bb";
public Map _persistenceInfo() { return litmap("a", false); }
}
static void test_structure_IPersistenceInfo() {
String blubb = shortClassName(test_structure_IPersistenceInfo_Blubb.class);
// only b is serialized according to _persistenceInfo()
assertEqualsVerbose(blubb + "(b=\"bb\")", structure(new test_structure_IPersistenceInfo_Blubb()));
}
enum test_structure_enum_Enum { a, b, c }
static void test_structure_enum() {
String s = structure(test_structure_enum_Enum.a);
assertEqualsVerbose("enum " + shortClassName(test_structure_enum_Enum.class) + " " + test_structure_enum_Enum.a.ordinal(), s);
assertSameVerbose(test_structure_enum_Enum.a, unstruct(s));
s = structure(test_structure_enum_Enum.b);
assertEqualsVerbose("enum " + shortClassName(test_structure_enum_Enum.class) + " " + test_structure_enum_Enum.b.ordinal(), s);
assertSameVerbose(test_structure_enum_Enum.b, unstruct(s));
}
static void test_structure_shouldIncludeField() {
structure_Data d = new structure_Data();
d.shouldIncludeField = field -> {
String c = shortClassName(field.getDeclaringClass());
String f = field.getName();
boolean shouldInclude = !(eq(c, "Pair") && eq(f, "a"));
printVars("shouldIncludeField", "c", c, "f", f, "shouldInclude", shouldInclude);
return shouldInclude;
};
String s = structure(pair(1, 2), d);
assertEqualsVerbose("Pair(b=2)", s);
}
static class test_structure_skipDefaultValues_X {
final public test_structure_skipDefaultValues_X setX(int x){ return x(x); }
public test_structure_skipDefaultValues_X x(int x) { this.x = x; return this; } final public int getX(){ return x(); }
public int x() { return x; }
int x = 1;
final public test_structure_skipDefaultValues_X setB(boolean b){ return b(b); }
public test_structure_skipDefaultValues_X b(boolean b) { this.b = b; return this; } final public boolean getB(){ return b(); }
public boolean b() { return b; }
boolean b = true;
final public test_structure_skipDefaultValues_X setC(boolean c){ return c(c); }
public test_structure_skipDefaultValues_X c(boolean c) { this.c = c; return this; } final public boolean getC(){ return c(); }
public boolean c() { return c; }
boolean c = false;
final public test_structure_skipDefaultValues_X setL(List l){ return l(l); }
public test_structure_skipDefaultValues_X l(List l) { this.l = l; return this; } final public List getL(){ return l(); }
public List l() { return l; }
List l = ll(1);
final public test_structure_skipDefaultValues_X setS(String s){ return s(s); }
public test_structure_skipDefaultValues_X s(String s) { this.s = s; return this; } final public String getS(){ return s(); }
public String s() { return s; }
String s;
}
static void testCase(String s, Object o) {
structure_Data d = new structure_Data();
d.skipDefaultValues(true);
String x = shortClassName(test_structure_skipDefaultValues_X.class);
s = migrateClassesInStructureText(s, "X", test_structure_skipDefaultValues_X.class);
assertEqualsVerbose(s, structure(o, d));
}
static void test_structure_skipDefaultValues() {
testCase("X", new test_structure_skipDefaultValues_X());
testCase("X(b=f)", new test_structure_skipDefaultValues_X().b(false));
testCase("X(c=t)", new test_structure_skipDefaultValues_X().c(true));
testCase("X(l=null)", new test_structure_skipDefaultValues_X().l(null));
testCase("X(s=\"hello\")", new test_structure_skipDefaultValues_X().s("hello"));
testCase("array{}", new Object[] {});
}
static class test_structure_customSerializer_X {
final public test_structure_customSerializer_X setI(int i){ return i(i); }
public test_structure_customSerializer_X i(int i) { this.i = i; return this; } final public int getI(){ return i(); }
public int i() { return i; }
int i;
// _serialize can now return this to request standard serialization
Object _serialize() {
return i < 0 ? this : i;
}
static test_structure_customSerializer_X _deserialize(Object o) {
return new test_structure_customSerializer_X().i((int) o);
}
public boolean equals(Object o) { return stdEq2(this, o); }
public int hashCode() { return stdHash2(this); }
}
static void test_structure_customSerializer() {
test_structure_customSerializer_X x = new test_structure_customSerializer_X().i(5);
String s = struct(x);
String nameOfX = shortClassName(test_structure_customSerializer_X.class);
assertEqualsVerbose("cu " + nameOfX + " 5", s);
assertEqualsVerbose(x, unstructure(s));
x = new test_structure_customSerializer_X().i(-5);
s = print(struct(x));
assertEqualsVerbose(x, unstructure(s));
}
static class test_structure_TransientObject_X implements TransientObject {
String member = "value";
}
static void test_structure_TransientObject() {
test_structure_TransientObject_X x = new test_structure_TransientObject_X();
assertEqualsVerbose("j " + quote(str(x)), struct(x));
}
static void test_structure_Color() {
testStructureFunction(Color.black);
testStructureFunction(Color.white);
}
static class test_unstructureErrorInConstructor_Oopsie { test_unstructureErrorInConstructor_Oopsie() { if (dynamicObjectIsLoading()) throw fail(); } }
static void test_unstructureErrorInConstructor() {
assertInstanceOf(DynamicObject.class, restructure(new test_unstructureErrorInConstructor_Oopsie()));
print("OK");
}
static void test_unstructure_jdkObject() {
Rectangle r = (Rectangle) (unstructure("java.awt.Rectangle(x=5)"));
assertEqualsVerbose(5, r.x);
}
static void test_structure_shortArrays() {
short[] a = { 0x1234, 0x5678 };
assertEqualsVerbose("shortarray \"12345678\"", struct(a));
assertEqualsVerbose(toList(a), toList(restruct(a)));
}
static void test_structure_longArrays() {
long[] a = { 0x1234567812345678L, 0xFEDCFEDC12343213L };
assertEqualsVerbose("longarray \"1234567812345678fedcfedc12343213\"", struct(a));
assertEqualsVerbose(toList(a), toList(restruct(a)));
}
static void test_structure_doubleArrays() {
double[] a = { 0.0, 1.0 };
assertEqualsVerbose("dblarray{d(\"0.0\"), d(\"1.0\")}", struct(a));
assertEqualsVerbose(toList(a), toList(restruct(a)));
}
static void test_structure_floatArrays() {
float[] a = { 0.0f, 1.0f };
assertEqualsVerbose("floatarray{fl \"0.0\", fl \"1.0\"}", struct(a));
assertEqualsVerbose(toList(a), toList(restruct(a)));
}
static void test_structure_fileAsKey() {
testStructureFunction(litmap(userDir() , true));
print("OK");
}
static void test_restructure_CompactHashMap() {
CompactHashMap map = new CompactHashMap();
CompactHashMap map2 = assertNotNull(restructureVerbose(map));
}
static void test_restructure_CompactHashSet() {
CompactHashSet set = new CompactHashSet();
CompactHashSet set2 = assertNotNull(restructureVerbose(set));
}
static void test_structure_floatingPoint() {
assertTrueVerbose("Nan", isNaN(restruct(Double.NaN)));
}
static void test_unstructureMissingClassObject() {
String s = "class(\"bla.notexistant\")";
DynamicObject o = (DynamicObject) (unstruct(s));
assertEqualsVerbose(Class.class.getName(), o.className);
assertEqualsVerbose("bla.notexistant", get("name", o));
assertEqualsVerbose(s, struct(o));
}
static class test_unstructure_doneLoading_Test {
int value;
public void _doneLoading() {
value = 5;
}
}
static void test_unstructure_doneLoading() {
test_unstructure_doneLoading_Test t = restructure(new test_unstructure_doneLoading_Test());
assertEqualsVerbose(5, t.value);
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static boolean printAlsoToSystemOut = true;
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(combinePrintParameters(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 = o + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
try {
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;
} catch (Throwable e) {
System.out.println(getStackTrace(e));
}
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);
if (printAlsoToSystemOut)
System.out.print(s);
vmBus_send("printed", mc(), s);
}
static void print_autoRotate() {
}
static AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static A assertEqualsVerbose(Object x, A y) {
assertEqualsVerbose((String) null, x, y);
return y;
}
// x = expected, y = actual
static A assertEqualsVerbose(String msg, Object x, A y) {
if (!eq(x, y)) {
throw fail((nempty(msg) ? msg + ": " : "") + "expected: "+ x + ", got: " + y);
} else
print("OK" + (empty(msg) ? "" : " " + msg) + ": " + /*sfu*/(x));
return y;
}
static void assertEqualsVerbose(Scorer scorer, Object x, Object y) { assertEqualsVerbose(scorer, "", x, y); }
static void assertEqualsVerbose(Scorer scorer, String msg, Object x, Object y) {
if (scorer == null) { assertEqualsVerbose(x, y); return; }
if (!eq(x, y)) {
print(appendColonIfNempty(msg) + y + " != " + x);
scorer.add(false);
} else {
print("OK: " + appendColonIfNempty(msg) + x);
scorer.add(true);
}
}
static String struct(Object o) {
return structure(o);
}
static String struct(Object o, structure_Data data) {
return structure(o, data);
}
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 stdEq2(Object a, Object b) {
if (a == null) return b == null;
if (b == null) return false;
if (a.getClass() != b.getClass()) return false;
for (String field : allFields(a))
if (neq(getOpt(a, field), getOpt(b, field)))
return false;
return true;
}
static int stdHash2(Object a) {
if (a == null) return 0;
return stdHash(a, toStringArray(allFields(a)));
}
static String testStructureFunction(Object input) {
return testStructureFunction(input, true);
}
static String testStructureFunction(Object input, boolean compare) {
String s;
{ long _startTime_0 = sysNow(); try {
s = structure(input);
} finally { _startTime_0 = sysNow()-_startTime_0; saveTiming(_startTime_0); } }
print("struct", shorten(s, 500));
Object o;
print("unstructuring " + l(s) + " chars");
{ long _startTime_1 = sysNow(); try {
o = unstructure(s);
} finally { _startTime_1 = sysNow()-_startTime_1; saveTiming(_startTime_1); } }
String x = structure(o);
assertEquals(s, x);
if (compare)
assertEqualsVerbose(input, o);
return x;
}
static A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
static List synchroList() {
return synchroList(new ArrayList ());
}
static List synchroList(List l) {
return new SynchronizedList(l);
}
static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static Class _getClass(Object o) {
return o == null ? null
: o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) {
try {
return classLoaderForObject(realm).loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static A restruct(A a) {
return restructure(a);
}
static List synchronizedList(List list) {
return synchroList(list);
}
static LinkedList litlinkedlist(A... a) {
LinkedList l = new LinkedList();
for (A x : a) l.add(x);
return l;
}
static boolean structure_showTiming, structure_checkTokenCount;
static String structure(Object o) {
return structure(o, new structure_Data());
}
static String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack))
popLast(d.stack).run();
}
static void structureToPrintWriter(Object o, PrintWriter out) { structureToPrintWriter(o, out, new structure_Data()); }
static void structureToPrintWriter(Object o, PrintWriter out, structure_Data d) {
d.out = out;
structure_go(o, d);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
// info on how to serialize objects of a certain class
static class structure_ClassInfo {
Class c;
String shortName;
List fields;
Method customSerializer;
IVF1 serializeObject; // can be set by caller of structure function
boolean special = false; // various special classes
boolean nullInstances = false; // serialize all instances as null (e.g. lambdas/anonymous classes)
boolean javafy = false; // always convert to "j ..."
Object emptyInstance; // to grab default field values from
public String toString() {
return commaCombine(
"Class " + className(c),
stringIf("special", special),
stringIf("customSerializer", customSerializer != null),
stringIf("javafy", javafy),
stringIf("nullInstances", nullInstances));
}
void nullInstances(boolean b) {
this.nullInstances = b;
if (b) special = true;
}
void javafy(boolean b) {
this.javafy = b;
if (b) special = true;
}
// overridable - return true if you wrote the object
boolean handle(A o) { return false; }
}
static class structure_Data {
PrintWriter out;
int stringSizeLimit;
int shareStringsLongerThan = 20;
boolean noStringSharing = false;
boolean storeBaseClasses = false;
boolean honorFieldOrder = true;
String mcDollar = actualMCDollar();
final public structure_Data setWarnIfUnpersistable(boolean warnIfUnpersistable){ return warnIfUnpersistable(warnIfUnpersistable); }
public structure_Data warnIfUnpersistable(boolean warnIfUnpersistable) { this.warnIfUnpersistable = warnIfUnpersistable; return this; } final public boolean getWarnIfUnpersistable(){ return warnIfUnpersistable(); }
public boolean warnIfUnpersistable() { return warnIfUnpersistable; }
boolean warnIfUnpersistable = true;
final public structure_Data setStackTraceIfUnpersistable(boolean stackTraceIfUnpersistable){ return stackTraceIfUnpersistable(stackTraceIfUnpersistable); }
public structure_Data stackTraceIfUnpersistable(boolean stackTraceIfUnpersistable) { this.stackTraceIfUnpersistable = stackTraceIfUnpersistable; return this; } final public boolean getStackTraceIfUnpersistable(){ return stackTraceIfUnpersistable(); }
public boolean stackTraceIfUnpersistable() { return stackTraceIfUnpersistable; }
boolean stackTraceIfUnpersistable = true;
// skip a field if it has the default value defined in the class
// -slower, and may cause issues with schema evolution
// -OTOH, it can serialize null values for a field with default non-null value
final public structure_Data setSkipDefaultValues(boolean skipDefaultValues){ return skipDefaultValues(skipDefaultValues); }
public structure_Data skipDefaultValues(boolean skipDefaultValues) { this.skipDefaultValues = skipDefaultValues; return this; } final public boolean getSkipDefaultValues(){ return skipDefaultValues(); }
public boolean skipDefaultValues() { return skipDefaultValues; }
boolean skipDefaultValues = false;
structure_Data d() { return this; }
transient IF1 shouldIncludeField;
boolean shouldIncludeField(Field f) { return shouldIncludeField != null ? shouldIncludeField.get(f) : shouldIncludeField_base(f); }
final boolean shouldIncludeField_fallback(IF1 _f, Field f) { return _f != null ? _f.get(f) : shouldIncludeField_base(f); }
boolean shouldIncludeField_base(Field f) { return true; }
IdentityHashMap seen = new IdentityHashMap();
//new BitSet refd;
HashMap strings = new HashMap();
HashSet concepts = new HashSet();
HashMap infoByClass = new HashMap();
// wrapper for _persistenceInfo field or _persistenceInfo method
// by class (taking the object instance)
HashMap> persistenceInfo = new HashMap();
int n; // token count
List stack = new ArrayList();
// append single token
structure_Data append(String token) { out.print(token); ++n; return this; }
structure_Data append(int i) { out.print(i); ++n; return this; }
// append multiple tokens
structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; }
// extend last token
structure_Data app(String token) { out.print(token); return this; }
structure_Data app(int i) { out.print(i); return this; }
structure_Data app(char c) { out.print(c); return this; }
structure_ClassInfo infoForClass(Class c) {
structure_ClassInfo info = infoByClass.get(c);
if (info == null) info = newClass(c);
return info;
}
transient IF1 realShortName;
String realShortName(String name) { return realShortName != null ? realShortName.get(name) : realShortName_base(name); }
final String realShortName_fallback(IF1 _f, String name) { return _f != null ? _f.get(name) : realShortName_base(name); }
String realShortName_base(String name) {
return dropPrefix("main$",
dropPrefix("loadableUtils.utils$",
dropPrefix(mcDollar, name)));
}
// called when a new class is detected
// can be overridden by clients
structure_ClassInfo newClass(Class c) {
// special classes here!
var d = d();
boolean isJavaXClass = isJavaXClassName(c.getName(), mcDollar);
printVars ("newClass", "c", c, "isJavaXClass", isJavaXClass);
if (c == String.class)
return new structure_ClassInfo() {
@Override boolean handle(String o) {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (!d.noStringSharing) {
if (d.shareStringsLongerThan == Integer.MAX_VALUE)
d.seen.put(o, d.n);
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, d.n);
}
quoteToPrintWriter(s, d.out); d.n++;
return true;
}
};
if (c == File.class)
return new structure_ClassInfo() {
@Override boolean handle(File o) {
append("File ").append(quote(o.getPath()));
return true;
}
};
if (!isJavaXClass) {
if (isSubClassOf(c, Set.class))
return new structure_ClassInfo() {
@Override boolean handle(Set o) {
writeSet(o);
return true;
}
};
if (isSubClassOf(c, Collection.class))
return new structure_ClassInfo() {
@Override boolean handle(Collection o) {
writeCollection(o);
return true;
}
};
if (isSubClassOf(c, Map.class))
return new structure_ClassInfo() {
@Override boolean handle(Map o) {
writeMap(o);
return true;
}
};
}
structure_ClassInfo info = new structure_ClassInfo();
info.c = c;
infoByClass.put(c, info);
String name = c.getName();
String shortName = realShortName(name);
if (startsWithDigit(shortName)) shortName = name; // for anonymous classes
info.shortName = shortName;
try {
if (isSyntheticOrAnonymous(c)) {
info.nullInstances(true);
return info;
}
if (c.isEnum()) {
info.special = true;
return info;
}
if (isSubClassOf(c, SynchronizedMap.class))
return new structure_ClassInfo() {
@Override boolean handle(SynchronizedMap o) {
append("sync ");
structure_1(o.m, d);
return true;
}
};
if (isSubClassOf(c, SynchronizedList.class))
return new structure_ClassInfo() {
@Override boolean handle(SynchronizedList o) {
append("sync ");
structure_1(unwrapSynchronizedList(o), d);
return true;
}
};
if (c.isArray()) {
// info.special?
return info;
}
if ((info.customSerializer = findMethodNamed(c, "_serialize"))
!= null) info.special = true;
if (storeBaseClasses) {
Class sup = c.getSuperclass();
if (sup != Object.class) {
append("bc ");
append(shortDynClassNameForStructure(c));
out.print(" ");
append(shortDynClassNameForStructure(sup));
out.print(" ");
infoForClass(sup); // transitively write out superclass relations
}
}
if (eqOneOf(name, "java.awt.Color", "java.lang.ThreadLocal"))
info.javafy(true);
else if (name.startsWith("sun") || !isPersistableClass(c)) {
info.javafy(true);
if (warnIfUnpersistable) {
String msg = "Class not persistable: " + c + " (anonymous or no default constructor), referenced from " + last(stack);
if (stackTraceIfUnpersistable)
printStackTrace(new Throwable(msg));
else
print(msg);
}
} else if (skipDefaultValues) {
var ctor = getDefaultConstructor(c);
if (ctor != null)
info.emptyInstance = invokeConstructor(ctor);
}
} catch (Throwable e) { printStackTrace(e);
info.nullInstances(true);
}
return info;
}
void setFields(structure_ClassInfo info, List fields) {
info.fields = fields;
}
void writeObject(Object o, String shortName, Map fv) {
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
append(shortName);
n += countDots(shortName)*2; // correct token count
print("Fields for " + shortName + ": " + fv.keySet());
int l = n;
Iterator it = fv.entrySet().iterator();
class WritingObject implements Runnable {
String lastFieldWritten;
public void run() { try {
if (!it.hasNext()) {
if (n != l)
append(")");
} else {
Map.Entry e = (Map.Entry) (it.next());
append(n == l ? "(" : ", ");
append(lastFieldWritten = (String) e.getKey()).append("=");
stack.add(this);
structure_1(e.getValue(), structure_Data.this);
}
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return shortName + "." + lastFieldWritten; }
}
stack.add(new WritingObject());
}
void writeMap(Map o) {
var d = this;
String name = o.getClass().getName();
if (o instanceof LinkedHashMap) d.append("lhm");
else if (o instanceof HashMap) d.append("hm");
else if (o instanceof TreeMap)
d.append(isCIMap_gen((TreeMap) o) ? "cimap" : "tm");
else if (name.equals("java.util.Collections$SynchronizedMap")
|| name.equals("java.util.Collections$SynchronizedSortedMap")
|| name.equals("java.util.Collections$SynchronizedNavigableMap")) {
d.append("sync ");
{ structure_1(unwrapSynchronizedMap(((Map) o)), d); return; }
}
d.append("{");
final int l = d.n;
final Iterator it = cloneMap((Map) o).entrySet().iterator();
class WritingMap implements Runnable {
boolean v = false;
Map.Entry e;
public String toString() {
return renderVars("WritingMap", "e" , mapEntryToPair(e), "v" , !v);
}
public void run() { try {
if (v) {
d.append("=");
v = false;
d.stack.add(this);
structure_1(e.getValue(), d);
} else {
if (!it.hasNext())
d.append("}");
else {
e = (Map.Entry) it.next();
v = true;
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(e.getKey(), d);
}
}
} catch (Exception __e) { throw rethrow(__e); } }
}
d.stack.add(new WritingMap());
}
void writeSet(Set o) {
var d = this;
String name = o.getClass().getName();
/*O set2 = unwrapSynchronizedSet(o);
if (set2 != o) {
d.append("sync");
o = set2;
} TODO */
if (o instanceof TreeSet) {
d.append(isCISet_gen(o) ? "ciset" : "treeset");
structure_1(new ArrayList(o), d);
return;
}
// assume it's a HashSet or LinkedHashSet
d.append(o instanceof LinkedHashSet ? "lhs" : "hashset");
structure_1(new ArrayList(o), d);
}
void writeCollection(Collection o) {
var d = this;
String name = o.getClass().getName();
print ("writeCollection", name);
if (name.equals("java.util.Collections$SynchronizedList")
|| name.equals("java.util.Collections$SynchronizedRandomAccessList")) {
d.append("sync ");
{ structure_1(unwrapSynchronizedList(((List) o)), d); return; }
}
else if (name.equals("java.util.LinkedList"))
d.append("ll");
d.append("[");
int l = d.n;
Iterator it = cloneList(o).iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext())
d.append("]");
else {
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.stack.add..."; }});
}
} // end of class structure_Data
static void structure_1(Object o, structure_Data d) { try {
if (o == null) { d.append("null"); return; }
Class c = o.getClass();
boolean concept = false;
concept = o instanceof Concept;
structure_ClassInfo info = d.infoForClass(c);
print ("structure_1 " + c);
boolean isJavaXName = isJavaXClassName(c.getName(), d.mcDollar);
boolean referencable = isJavaXName &&
!(o instanceof Number || o instanceof Character || o instanceof Boolean)
|| o instanceof Collection || o instanceof Map;
printVars ("isJavaXName", isJavaXName, "referencable", referencable, "mcDollar" , d.mcDollar);
if (referencable) {
Integer ref = d.seen.get(o);
print ("Existing reference " + className(ref));
if (ref != null) {
//d.refd.set(ref);
d.append("t").app(ref);
return;
}
d.seen.put(o, d.n); // record token number
print ("Recorded reference " + d.n);
}
if (info.handle(o)) {
print ("handled by " + className(info));
return;
}
if (info.special) {
if (info.javafy) {
d.append("j ").append(quote(str(o))); return; // This is not unstructure-able except for java.awt.Color
}
if (c.isEnum()) {
d.append("enum ");
d.append(info.shortName);
d.out.append(' ');
d.append(((Enum) o).ordinal());
return;
}
if (info.customSerializer != null) {
// custom serialization (_serialize method)
Object o2 = invokeMethod(info.customSerializer, o);
if (o2 == o) {} // bail out to standard serialization
else {
d.append("cu ");
String name = c.getName();
String shortName = d.realShortName(name);
d.append(shortName);
d.out.append(' ');
structure_1(o2, d);
return;
}
} else if (info.nullInstances) { d.append("null"); return; }
else if (info.serializeObject != null)
{ info.serializeObject.get(o); return; }
else throw fail("unknown special type");
}
List lFields = info.fields;
if (lFields == null) {
// these are never back-referenced (for readability)
if (o instanceof Number) {
PrintWriter out = d.out;
if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; }
if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; }
if (o instanceof Short) { short s = ((Short) o).shortValue(); d.append("sh "); out.print(s); d.n += s < 0 ? 2 : 1; return; }
if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; }
if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; }
if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; }
}
if (o instanceof Boolean) {
d.append(((Boolean) o).booleanValue() ? "t" : "f"); return;
}
if (o instanceof Character) {
d.append(quoteCharacter((Character) o)); return;
}
String name = c.getName();
if (!isJavaXName) {
if (o instanceof Set)
{ d.writeSet((Set) o); return; }
if (o instanceof Collection
/* && neq(name, "main$Concept$RefL") */) {
{ d.writeCollection((Collection) o); return; }
}
if (o instanceof Map)
{ d.writeMap((Map) o); return; }
}
if (c.isArray()) {
if (o instanceof byte[]) {
d.append("ba ").append(quote(bytesToHex((byte[]) o))); return;
}
final int n = Array.getLength(o);
if (o instanceof boolean[]) {
String hex = boolArrayToHex((boolean[]) o);
int i = l(hex);
while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2;
d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return;
}
if (o instanceof short[]) {
String hex = shortArrayToHex_bigEndian((short[]) o);
d.append("shortarray \"").append(hex).app('\"');
return;
}
if (o instanceof long[]) {
String hex = longArrayToHex_bigEndian((long[]) o);
d.append("longarray \"").append(hex).app('\"');
return;
}
String atype = "array"/*, sep = ", "*/; // sep is not used yet
if (o instanceof int[]) {
//ret "intarray " + quote(intArrayToHex((int[]) o));
atype = "intarray";
//sep = " ";
} else if (o instanceof double[]) {
atype = "dblarray";
//sep = " ";
} else if (o instanceof float[]) {
atype = "floatarray";
} else {
// 2-dimensional and deeper arrays
Pair p = arrayTypeAndDimensions(c);
if (p.a == int.class) atype = "intarray";
else if (p.a == byte.class) atype = "bytearray";
else if (p.a == boolean.class) atype = "boolarray";
else if (p.a == double.class) atype = "dblarray";
else if (p.a == float.class) atype = "floatarray";
else if (p.a == String.class) { atype = "array S"; d.n++; }
else atype = "array"; // fail("Unsupported array type: " + p.a);
if (p.b > 1) {
atype += "/" + p.b; // add number of dimensions
d.n += 2; // 2 additional tokens will be written
}
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0) d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
if (d.n != l) d.append(", ");
d.append(i);
}
d.append("}"); return;
}
/*if (name.equals("main$Lisp")) {
fail("lisp not supported right now");
}*/
String dynName = shortDynClassNameForStructure(o);
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
// serialize an object with fields.
// first, collect all fields and values in fv.
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
Class cc = c;
while (cc != Object.class) {
for (Field field : getDeclaredFields_cached(cc)) {
if (!d.shouldIncludeField(field)) continue;
String fieldName = field.getName();
if (fieldName.equals("_persistenceInfo"))
d.persistenceInfo.put(c, obj -> (Map) fieldGet(field, obj));
if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
continue;
fields.add(field);
// put special cases here...?
}
cc = cc.getSuperclass();
}
Method persistenceInfoMethod = findInstanceMethod(c, "_persistenceInfo");
if (persistenceInfoMethod != null)
d.persistenceInfo.put(c, obj -> (Map) invokeMethod(persistenceInfoMethod, obj));
lFields = asList(d.honorFieldOrder ? fieldObjectsInFieldOrder(c, fields) : fields);
// Render this$0/this$1 first because unstructure needs it for constructor call.
int n = l(lFields);
for (int i = 0; i < n; i++) {
Field f = lFields.get(i);
if (f.getName().startsWith("this$")) {
lFields.remove(i);
lFields.add(0, f);
break;
}
}
print("Saving fields for " + c + ": " + lFields);
d.setFields(info, lFields);
} // << if (lFields == null)
// get _persistenceInfo from field and/or dynamic field
IF1 piGetter = d.persistenceInfo.get(c);
Map persistenceInfo = piGetter == null ? null : piGetter.get(o);
if (piGetter == null && o instanceof DynamicObject)
persistenceInfo = (Map) getOptDynOnly(((DynamicObject) o), "_persistenceInfo");
print("persistenceInfo for " + c + ": " + persistenceInfo);
LinkedHashMap fv = new LinkedHashMap();
Object defaultInstance = info.emptyInstance;
for (Field f : lFields) {
Object value, defaultValue = null;
try {
value = f.get(o);
defaultValue = defaultInstance == null ? null : f.get(defaultInstance);
} catch (Exception e) {
value = "?";
}
if (!eq(defaultValue, value) && (persistenceInfo == null
|| !Boolean.FALSE.equals(persistenceInfo.get(f.getName()))))
fv.put(f.getName(), value);
else print("Skipping default value " + defaultValue + " of " + f.getName() + " for " + identityHashCode(o));
}
String shortName = info.shortName;
// Now we have fields & values. Process fieldValues if it's a DynamicObject.
Object classNameFromFV = fv.get("className");
// omit field "className" if equal to class's name
if (concept && eq(classNameFromFV, shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
putAll(fv, (Map) fv.get("fieldValues"));
fv.remove("fieldValues");
if (((DynamicObject) o).className != null) {
// TODO: this probably doesn't work with inner classes
shortName = shortDynClassNameForStructure((DynamicObject) o);
fv.remove("className");
// special handling for missing Class objects encoded as DynamicObject
if (eq(shortName, "java.lang.Class")) {
d.append("class(");
d.append(quoted(fv.get("name")));
d.append(")");
return;
}
}
}
d.writeObject(o, shortName, fv);
} catch (Exception __e) { throw rethrow(__e); } }
static A restructure(A a) {
return (A) unstructure(structure(a));
}
static A assertEquals(Object x, A y) {
return assertEquals("", 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 void assertEquals(Scorer scorer, Object x, Object y) {
assertEquals(scorer, "", x, y);
}
static void assertEquals(Scorer scorer, String msg, Object x, Object y) {
if (scorer == null) { assertEquals(msg, x, y); return; }
scorer.add(eq(x, y), nullIfEmpty(msg));
}
static void assertTrueVerbose(Object o) {
assertEqualsVerbose(true, o);
}
static void assertTrueVerbose(String msg, Object o) {
assertEqualsVerbose(msg, true, o);
}
static List unwrapSynchronizedList(List l) {
if (l instanceof SynchronizedList) return ((SynchronizedList) l).list;
if (eqOneOf(className(l),
"java.util.Collections$SynchronizedList",
"java.util.Collections$SynchronizedRandomAccessList"))
return (List) get_raw(l, "list");
return l;
}
// TODO: cyclic structures involving certain lists & sets
static Object unstructure(String text) {
return unstructure(text, false);
}
static Object unstructure(String text, boolean allDynamic) {
return unstructure(text, allDynamic, null);
}
static Object unstructure(String text, IF1 classFinder) {
return unstructure(text, false, classFinder);
}
static int structure_internStringsLongerThan = 50;
static int unstructure_unquoteBufSize = 100;
static int unstructure_tokrefs; // stats
abstract static class unstructure_Receiver {
abstract void set(Object o);
}
// classFinder: func(name) -> class (optional)
static Object unstructure(String text, boolean allDynamic,
Object classFinder) {
if (text == null) return null;
return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
}
static Object unstructure_reader(BufferedReader reader) {
return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
}
interface unstructure_Handler {
void parse(int refID, int tokIndex, unstructure_Receiver out);
}
static class Unstructurer {
final public Unstructurer setTok(Producer tok){ return tok(tok); }
public Unstructurer tok(Producer tok) { this.tok = tok; return this; } final public Producer getTok(){ return tok(); }
public Producer tok() { return tok; }
Producer tok;
final public Unstructurer setAllDynamic(boolean allDynamic){ return allDynamic(allDynamic); }
public Unstructurer allDynamic(boolean allDynamic) { this.allDynamic = allDynamic; return this; } final public boolean getAllDynamic(){ return allDynamic(); }
public boolean allDynamic() { return allDynamic; }
boolean allDynamic = false;
int i = -1;
Object classFinder;
String mcDollar = actualMCDollar();
Unstructurer classFinder(Object _classFinder) {
classFinder = _classFinder != null ? _classFinder : _defaultClassFinder();
return this;
}
// use Eclipse primitive collection if possible (smaller & hopefully faster?)
HashMap refs = new HashMap();
HashMap tokrefs = new HashMap();
HashSet concepts = new HashSet();
List stack = new ArrayList();
Map baseClassMap = new HashMap();
HashMap innerClassConstructors = new HashMap();
String curT;
char[] unquoteBuf = new char[unstructure_unquoteBufSize];
// value is a class or a Handler
final HashMap handlers = new HashMap();
Unstructurer() {
try {
Class mc = (Class) (callF(classFinder, ""));
if (mc != null) mcDollar = mc.getName() + "$";
} catch (Throwable __e) { pcallFail(__e); }
makeHandlers();
}
void makeHandlers() {
unstructure_Handler h;
handlers.put("bigint", (unstructure_Handler) (refID, tokIndex, out)
-> out.set(parseBigInt()));
handlers.put("d", (unstructure_Handler) (refID, tokIndex, out)
-> out.set(parseDouble()));
handlers.put("fl", (unstructure_Handler) (refID, tokIndex, out)
-> out.set(parseFloat()));
handlers.put("sh", (unstructure_Handler) (refID, tokIndex, out) -> {
consume();
String t = tpp();
if (t.equals("-")) {
t = tpp();
out.set((short) (-parseInt(t))); return;
}
out.set((short) parseInt(t));
});
handlers.put("enum", (unstructure_Handler) (refID, tokIndex, out) -> {
consume();
String t = tpp();
assertTrue(isJavaIdentifier(t));
String fullClassName = mcDollar + t;
Class _c = findAClass(fullClassName);
if (_c == null) throw fail("Enum class not found: " + fullClassName);
int ordinal = parseInt(tpp());
out.set(_c.getEnumConstants()[ordinal]);
});
handlers.put("false", h = (unstructure_Handler) (refID, tokIndex, out) -> {
consume(); out.set(false);
});
handlers.put("f", h);
handlers.put("true", h = (unstructure_Handler) (refID, tokIndex, out) -> {
consume(); out.set(true);
});
handlers.put("t", h);
handlers.put("{", (unstructure_Handler) (refID, tokIndex, out) -> parseMap(out));
handlers.put("[", (unstructure_Handler) (refID, tokIndex, out) -> {
ArrayList l = new ArrayList();
if (refID >= 0) refs.put(refID, l);
this.parseList(l, out);
});
handlers.put("bitset", (unstructure_Handler) (refID, tokIndex, out) -> parseBitSet(out));
handlers.put("array", h = (unstructure_Handler) (refID, tokIndex, out) -> parseArray(out));
handlers.put("intarray", h);
handlers.put("dblarray", h);
handlers.put("floatarray", h);
handlers.put("shortarray", (unstructure_Handler) (refID, tokIndex, out) -> {
consume();
String hex = trivialUnquote(tpp());
out.set(shortArrayFromBytes(hexToBytes(hex)));
});
handlers.put("longarray", (unstructure_Handler) (refID, tokIndex, out) -> {
consume();
String hex = trivialUnquote(tpp());
out.set(longArrayFromBytes(hexToBytes(hex)));
});
} // end of makeHandlers - add more handlers here
Class findAClass(String fullClassName) { try {
return classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
} catch (Throwable __e) { return null; } }
String unquote(String s) {
return unquoteUsingCharArray(s, unquoteBuf);
}
// look at current token
String t() {
return curT;
}
// get current token, move to next
String tpp() {
String t = curT;
consume();
return t;
}
void parse(final unstructure_Receiver out) {
String t = t();
int refID;
if (structure_isMarker(t, 0, l(t))) {
refID = parseInt(t.substring(1));
consume();
} else refID = -1;
// if (debug) print("parse: " + quote(t));
final int tokIndex = i;
parse_inner(refID, tokIndex, new unstructure_Receiver() {
void set(Object o) {
if (refID >= 0)
refs.put(refID, o);
if (o != null)
tokrefs.put(tokIndex, o);
out.set(o);
}
});
}
void parse_inner(int refID, int tokIndex, unstructure_Receiver out) {
String t = t();
// if (debug) print("parse_inner: " + quote(t));
Object handler = handlers.get(t);
if (handler instanceof unstructure_Handler)
{ ((unstructure_Handler) handler).parse(refID, tokIndex, out); return; }
Class c = (Class) handler;
if (c == null) {
if (t.startsWith("\"")) {
String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
out.set(s); return;
}
if (t.startsWith("'")) {
out.set(unquoteCharacter(tpp())); return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
//if (debug) print("isLongConstant " + quote(t) + " => " + isLongConstant(t));
if (isLongConstant(t)) {
out.set(parseLong(t)); return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
//if (debug) print("isLongConstant " + quote(t) + " => " + isLongConstant(t));
if (isLongConstant(t)) {
out.set(parseLong(t)); return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return;
}
if (t.equals("File")) {
consume();
File f = new File(unquote(tpp()));
out.set(f); return;
}
if (t.startsWith("r") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = refs.get(ref);
if (o == null)
warn("unsatisfied back reference " + ref);
out.set(o); return;
}
if (t.startsWith("t") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = tokrefs.get(ref);
if (o == null)
warn("unsatisfied token reference " + ref + " at " + tokIndex);
out.set(o); return;
}
if (t.equals("hashset")) { parseHashSet(out); return; }
if (t.equals("lhs")) { parseLinkedHashSet(out); return; }
if (t.equals("treeset")) { parseTreeSet(out); return; }
if (t.equals("ciset")) { parseCISet(out); return; }
if (eqOneOf(t, "hashmap", "hm")) {
consume();
parseMap(new HashMap(), out);
return;
}
if (t.equals("lhm")) {
consume();
parseMap(new LinkedHashMap(), out);
return;
}
if (t.equals("tm")) {
consume();
parseMap(new TreeMap(), out);
return;
}
if (t.equals("cimap")) {
consume();
parseMap(ciMap(), out);
return;
}
if (t.equals("ll")) {
consume();
LinkedList l = new LinkedList();
if (refID >= 0) refs.put(refID, l);
{ parseList(l, out); return; }
}
if (t.equals("syncLL")) { // legacy
consume();
{ parseList(synchroLinkedList(), out); return; }
}
if (t.equals("sync")) {
consume();
{ parse(new unstructure_Receiver() {
void set(Object value) {
if (value instanceof Map) {
// Java 7
if (value instanceof NavigableMap)
{ out.set(synchroNavigableMap((NavigableMap) value)); return; }
if (value instanceof SortedMap)
{ out.set(synchroSortedMap((SortedMap) value)); return; }
{ out.set(synchroMap((Map) value)); return; }
} else
{ out.set(synchroList((List) value)); return; }
}
}); return; }
}
if (t.equals("ba")) {
consume();
String hex = trivialUnquote(tpp());
out.set(hexToBytes(hex)); return;
}
if (t.equals("boolarray")) {
consume();
int n = parseInt(tpp());
String hex = trivialUnquote(tpp());
out.set(boolArrayFromBytes(hexToBytes(hex), n)); return;
}
if (t.equals("class")) {
out.set(parseClass()); return;
}
if (t.equals("l")) {
parseLisp(out); return;
}
if (t.equals("null")) {
consume(); out.set(null); return;
}
if (eq(t, "c")) {
consume();
t = t();
assertTrue(isJavaIdentifier(t));
concepts.add(t);
}
// custom deserialization (new static method method)
if (eq(t, "cu")) {
consume();
t = tpp();
assertTrue(isJavaIdentifier(t));
String fullClassName = mcDollar + t;
Class _c = findAClass(fullClassName);
if (_c == null) throw fail("Class not found: " + fullClassName);
parse(new unstructure_Receiver() {
void set(Object value) {
out.set(call(_c, "_deserialize", value));
}
});
return;
}
}
if (eq(t, "j")) {
consume();
out.set(parseJava()); return;
}
if (eq(t, "bc")) {
consume();
String c1 = tpp();
String c2 = tpp();
baseClassMap.put(c1, c2);
{ parse_inner(refID, i, out); return; }
}
// add more tokens here
// Now we want to find our target class c
// Have we failed to look up the class before?
//bool seenBefore = handlers.containsKey(cname);
// If we have seen the class before, we skip all of this
// and simply leave c as null
// TODO - how do we fill className?
//if (!seenBefore) {
if (c == null && !isJavaIdentifier(t))
throw new RuntimeException("Unknown token " + (i+1) + ": " + quote(t));
// any other class name (or package name)
consume();
String className, fullClassName;
// Is it a package name?
if (eq(t(), ".")) {
className = t;
do {
consume();
className += "." + assertIdentifier(tpp());
} while (eq(t(), "."));
fullClassName = className;
} else {
className = t;
fullClassName = mcDollar + t;
}
if (c == null && !allDynamic) {
// First, find class
c = findAClass(fullClassName);
handlers.put(className, c);
}
// check for existing base class
if (c == null && !allDynamic) {
Set seen = new HashSet();
String parent = className;
while (true) {
String baseName = baseClassMap.get(parent);
if (baseName == null)
break;
if (!seen.add(baseName))
throw fail("Cyclic superclass info: " + baseName);
c = findAClass(mcDollar + baseName);
if (c == null)
print("Base class " + baseName + " of " + parent + " doesn't exist either");
else if (isAbstract(c))
print("Can't instantiate abstract base class: " + c);
else {
printVars_str("Reverting to base class", "className", className, "baseName", baseName, "c", c);
handlers.put(className, c);
break;
}
parent = baseName;
}
}
//}
// Check if it has an outer reference
boolean hasBracket = eq(t(), "(");
if (hasBracket) consume();
boolean hasOuter = hasBracket && startsWith(t(), "this$");
DynamicObject dO = null;
Object o = null;
final String thingName = t;
try {
if (c != null) {
if (hasOuter) try {
Constructor ctor = innerClassConstructors.get(c);
if (ctor == null)
innerClassConstructors.put(c, ctor = nuStubInnerObject_findConstructor(c, classFinder));
o = ctor.newInstance(new Object[] {null});
} catch (Exception e) {
print("Error deserializing " + c + ": " + e);
o = nuEmptyObject(c);
} else
o = nuEmptyObject(c);
if (o instanceof DynamicObject) dO = (DynamicObject) o;
} else {
if (concepts.contains(t) && (c = findAClass(mcDollar + "Concept")) != null)
o = dO = (DynamicObject) nuEmptyObject(c);
else
dO = new DynamicObject();
dO.className = className;
}
} catch (Throwable __e) { pcallFail(__e); } // end of pcall
// Creating instance failed? Use DynamicObject
if (o == null && dO == null)
dO = new DynamicObject();
// Save in references list early because contents of object
// might link back to main object
if (refID >= 0)
refs.put(refID, o != null ? o : dO);
tokrefs.put(tokIndex, o != null ? o : dO);
// NOW parse the fields!
HashMap fields = new HashMap(); // no longer preserving order (why did we do this?)
Object _o = o;
DynamicObject _dO = dO;
if (hasBracket) {
stack.add(new Runnable() { public void run() { try {
if (eq(t(), ",")) consume();
if (eq(t(), ")")) {
consume(")");
objRead(_o, _dO, fields, hasOuter);
out.set(_o != null ? _o : _dO);
} else {
final String key = unquote(tpp());
String t = tpp();
if (!eq(t, "="))
throw fail("= expected, got " + t + " after " + quote(key) + " in object " + thingName /*+ " " + sfu(fields)*/);
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object value) {
fields.put(key, value);
/*ifdef unstructure_debug
print("Got field value " + value + ", next token: " + t());
endifdef*/
//if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef unstructure_debug\r\n print(\"in object values, token: \" + t());\r..."; }});
} else {
objRead(o, dO, fields, hasOuter);
out.set(o != null ? o : dO);
}
}
void objRead(Object o, DynamicObject dO, Map fields, boolean hasOuter) {
// translate between diferent compilers (this$0 vs this$1)
Object outer = fields.get("this$0");
if (outer != null) fields.put("this$1", outer);
else {
outer = fields.get("this$1");
if (outer != null) fields.put("this$0", outer);
}
if (o != null) {
if (dO != null) {
setOptAllDyn_pcall(dO, fields);
} else {
setOptAll_pcall(o, fields);
}
if (hasOuter)
fixOuterRefs(o);
} else for (Map.Entry e : fields.entrySet())
setDynObjectValue(dO, intern(e.getKey()), e.getValue());
if (o != null)
pcallOpt_noArgs(o, "_doneLoading");
}
void parseSet(final Set set, final unstructure_Receiver out) {
this.parseList(new ArrayList(), new unstructure_Receiver() {
void set(Object o) {
set.addAll((List) o);
out.set(set);
}
});
}
void parseLisp(final unstructure_Receiver out) {
throw fail("class Lisp not included");
}
void parseBitSet(final unstructure_Receiver out) {
consume("bitset");
consume("{");
final BitSet bs = new BitSet();
stack.add(new Runnable() { public void run() { try {
if (eq(t(), "}")) {
consume("}");
out.set(bs);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
bs.set((Integer) o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n } els..."; }});
}
void parseList(final List list, final unstructure_Receiver out) {
tokrefs.put(i, list);
consume("[");
stack.add(new Runnable() { public void run() { try {
if (eq(t(), "]")) {
consume();
out.set(list);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
//if (debug) print("List element type: " + getClassName(o));
list.add(o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"]\")) {\r\n consume();\r\n ifdef unstructure_debug\r\n ..."; }});
}
void parseArray(unstructure_Receiver out) {
String _type = tpp();
int dims;
if (eq(t(), "S")) { // string array
_type = "S";
consume();
}
if (eq(t(), "/")) { // multi-dimensional array
consume();
dims = parseInt(tpp());
} else
dims = 1;
consume("{");
List list = new ArrayList();
String type = _type;
stack.add(new Runnable() { public void run() { try {
if (eq(t(), "}")) {
consume("}");
if (dims > 1) {
Class atype;
if (type.equals("intarray")) atype = int.class;
else if (type.equals("S")) atype = String.class;
else throw todo("multi-dimensional arrays of other types");
out.set(list.toArray((Object[]) newMultiDimensionalOuterArray(atype, dims, l(list))));
} else
out.set(
type.equals("intarray") ? toIntArray(list)
: type.equals("dblarray") ? toDoubleArray(list)
: type.equals("floatarray") ? toFloatArray(list)
: type.equals("S") ? toStringArray(list)
: list.toArray());
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
list.add(o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n if (dims > 1) {\r\n ..."; }});
}
Object parseClass() {
consume("class");
consume("(");
String name = unquote(tpp());
consume(")");
Class c = allDynamic ? null : findAClass(name);
if (c != null) return c;
DynamicObject dO = new DynamicObject();
dO.className = "java.lang.Class";
name = dropPrefix(mcDollar, name);
dynamicObject_setRawFieldValue(dO, "name", name);
return dO;
}
Object parseBigInt() {
consume("bigint");
consume("(");
String val = tpp();
if (eq(val, "-"))
val = "-" + tpp();
consume(")");
return new BigInteger(val);
}
Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tpp());
consume(")");
return Double.parseDouble(val);
}
Object parseFloat() {
consume("fl");
String val;
if (eq(t(), "(")) {
consume("(");
val = unquote(tpp());
consume(")");
} else {
val = unquote(tpp());
}
return Float.parseFloat(val);
}
void parseHashSet(unstructure_Receiver out) {
consume("hashset");
parseSet(new HashSet(), out);
}
void parseLinkedHashSet(unstructure_Receiver out) {
consume("lhs");
parseSet(new LinkedHashSet(), out);
}
void parseTreeSet(unstructure_Receiver out) {
consume("treeset");
parseSet(new TreeSet(), out);
}
void parseCISet(unstructure_Receiver out) {
consume("ciset");
parseSet(ciSet(), out);
}
void parseMap(unstructure_Receiver out) {
parseMap(new TreeMap(), out);
}
Object parseJava() {
String j = unquote(tpp());
Matches m = new Matches();
if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
else {
warn("Unknown Java object: " + j);
return null;
}
}
void parseMap(final Map map, final unstructure_Receiver out) {
consume("{");
stack.add(new Runnable() {
boolean v = false;
Object key;
public void run() {
if (v) {
v = false;
stack.add(this);
if (!eq(tpp(), "="))
throw fail("= expected, got " + t() + " in map of size " + l(map));
parse(new unstructure_Receiver() {
void set(Object value) {
map.put(key, value);
if (eq(t(), ",")) consume();
}
});
} else {
if (eq(t(), "}")) {
consume("}");
out.set(map);
} else {
v = true;
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
key = o;
}
});
}
} // if v else
} // run()
});
}
/*void parseSub(unstructure_Receiver out) {
int n = l(stack);
parse(out);
while (l(stack) > n)
stack
}*/
void consume() { curT = tok.next(); ++i; }
void consume(String s) {
if (!eq(t(), s)) {
/*S prevToken = i-1 >= 0 ? tok.get(i-1) : "";
S nextTokens = join(tok.subList(i, Math.min(i+2, tok.size())));
fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");*/
throw fail(quote(s) + " expected, got " + quote(t()));
}
consume();
}
// outer wrapper function getting first token and unwinding the stack
void parse_initial(unstructure_Receiver out) {
consume(); // get first token
parse(out);
while (nempty(stack))
popLast(stack).run();
}
}
static Object unstructure_tok(Producer tok, boolean allDynamic, Object classFinder) {
boolean debug = unstructure_debug;
AutoCloseable __1 = tempSetTL(dynamicObjectIsLoading_threadLocal(), true); try {
Var v = new Var();
var unstructurer = new Unstructurer()
.tok(tok)
.allDynamic(allDynamic)
.classFinder(classFinder);
unstructurer.parse_initial(new unstructure_Receiver() {
void set(Object o) { v.set(o); }
});
unstructure_tokrefs = unstructurer.tokrefs.size();
return v.get();
} finally { _close(__1); }}
static boolean unstructure_debug = false;
static void assertTrue(Object o) {
if (!(eq(o, true) /*|| isTrue(pcallF(o))*/))
throw fail(str(o));
}
static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static boolean assertTrue(Scorer scorer, boolean b) {
scorer.add(b);
return b;
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null) for (A x : a) l.add(x);
return l;
}
static Map synchroLinkedHashMap() {
return synchronizedMap(new LinkedHashMap());
}
// works for both java.util-wrapped maps as well as our own
static Map unwrapSynchronizedMap(Map map) {
if (eqOneOf(shortClassName(map),
"SynchronizedMap",
"SynchronizedSortedMap",
"SynchronizedNavigableMap"))
return (Map) get_raw(map, "m");
return map;
}
static SortedMap synchronizedTreeMap() {
return synchroTreeMap();
}
static String className(Object o) {
return getClassName(o);
}
static Object unstruct(String text) {
return unstructure(text);
}
static Pair pair(A a, B b) {
return new Pair(a, b);
}
static Pair pair(A a) {
return new Pair(a, a);
}
static List> mapToPairs(Map map) {
List> l = emptyList(l(map));
if (map != null) for (Map.Entry e : map.entrySet())
l.add(pair(e.getKey(), e.getValue()));
return l;
}
static Map synchronizedMap() {
return synchroMap();
}
static Map synchronizedMap(Map map) {
return synchroMap(map);
}
static int shorten_default = 100;
static String shorten(CharSequence s) { return shorten(s, shorten_default); }
static String shorten(CharSequence s, int max) {
return shorten(s, max, "...");
}
static String shorten(CharSequence s, int max, String shortener) {
if (s == null) return "";
if (max < 0) return str(s);
return s.length() <= max ? str(s) : subCharSequence(s, 0, min(s.length(), max-l(shortener))) + shortener;
}
static String shorten(int max, CharSequence s) { return shorten(s, max); }
static List unstructureList(String s) {
return (List) unstructure(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(IMultiSet ms) { return ms == null ? 0 : ms.size(); }
static int l(IMultiMap mm) { return mm == null ? 0 : mm.size(); }
static int l(IntSize o) { return o == null ? 0 : o.size(); }
static void assertSame(Object a, Object b) { assertSame("", a, b); }
static void assertSame(String msg, Object a, Object b) {
if (a != b)
throw fail(joinNemptiesWithColon(msg, a + " != " + b + " (" + identityHash(a) + "/" + identityHash(b) + ")"));
}
static void assertSame(IF0 msg, Object a, Object b) {
if (a != b)
throw fail(joinNemptiesWithColon(msg.get(), a + " != " + b + " (" + identityHash(a) + "/" + identityHash(b) + ")"));
}
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 Pair first(Map map) {
return mapEntryToPair(first(entrySet(map)));
}
static Pair first(MultiMap mm) {
if (mm == null) return null;
var e = first(mm.data.entrySet());
if (e == null) return null;
return pair(e.getKey(), first(e.getValue()));
}
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 Character first(CharSequence s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static A first(T3 t) {
return t == null ? null : t.a;
}
static Byte first(byte[] l) { return empty(l) ? null : l[0]; }
static Double first(double[] l) { return empty(l) ? null : l[0]; }
static A first(A[] l, IF1 pred) {
return firstThat(l, pred);
}
static A first(Iterable l, IF1 pred) {
return firstThat(l, pred);
}
static A first(IF1 pred, Iterable l) {
return firstThat(pred, l);
}
static A first(AppendableChain a) {
return a == null ? null : a.element;
}
static A first(IMultiSet a) {
return a == null ? null : first(a.keySet());
}
static boolean eqOneOf(Object o, Object... l) {
if (l != null) for (Object x : l) if (eq(o, x)) return true; return false;
}
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 B callF(A a, IF1 f) {
return f == null ? null : f.get(a);
}
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 void callF(A a, IVF1 f) {
if (f != null) f.get(a);
}
static void callF(IVF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Runnable r) { { if (r != null) r.run(); } return null; }
static Object callF(Object f, Object... args) {
return safeCallF(f, args);
}
static Object safeCallF(Object f, Object... 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) {
if (f instanceof String)
throw fail("Legacy call: " + f);
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));
}
// 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 Object _defaultClassFinder_value = defaultDefaultClassFinder();
static Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
// make concept instance that is not connected to DB
static A unlisted(Class c, Object... args) {
concepts_unlisted.set(true);
try {
return nuObject(c, args);
} finally {
concepts_unlisted.set(null);
}
}
static Concept unlisted(String name, Object... args) {
Class extends Concept> cc = findClass(name);
concepts_unlisted.set(true);
try {
return cc != null ? nuObject(cc) : new Concept(name);
} finally {
concepts_unlisted.set(null);
}
}
static void assertSameVerbose(Object x, Object y) {
assertSameVerbose((String) null, x, y);
}
static void assertSameVerbose(String msg, Object x, Object y) {
if (x != y)
throw fail((msg != null ? msg + ": " : "") + str_shorten(y) + " !== " + str_shorten(x));
else
print("OK: " + str_shorten(x));
}
static Object cget(Object c, String field) {
c = derefRef(c);
Object o = getOpt(c, field);
return derefRef(o);
}
static Object cget(String field, Object c) {
return cget(c, field);
}
static ArrayList toList(A[] a) { return asList(a); }
static ArrayList toList(int[] a) { return asList(a); }
static ArrayList toList(short[] a) { return asList(a); }
static ArrayList toList(long[] a) { return asList(a); }
static ArrayList toList(double[] a) { return asList(a); }
static ArrayList toList(float[] a) { return asList(a); }
static ArrayList toList(Set s) { return asList(s); }
static ArrayList toList(Iterable s) { return asList(s); }
static List lmap(IF1 f, Iterable l) {
return lambdaMap(f, l);
}
static List lmap(IF1 f, A[] l) {
return lambdaMap(f, l);
}
static HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static void litmap_impl(Map map, Object... x) {
if (x != null) for (int i = 0; i < x.length-1; i += 2)
if (x[i+1] != null)
map.put(x[i], x[i+1]);
}
static A nuDyn(Class c, Object... values) {
A a = nuObject(c);
setOptAllDyn(a, paramsToMap(values));
return a;
}
static A restructureVerbose(A a) {
return (A) unstructure(print("structure", structure(a)));
}
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 boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
// a little kludge for stuff like eq(symbol, "$X")
static boolean eq(Symbol a, String b) {
return eq(str(a), b);
}
// Use like this: printVars(+x, +y);
// Or: printVars("bla", +x);
// Or: printVars bla(, +x);
static void printVars(Object... params) {
printVars_str(params);
}
static String b(Object contents, Object... params) {
return fulltag("b", contents, params);
}
static String migrateClassesInStructureText(String s, Object... migrations) {
List tok = javaTokForStructure(s);
int n = l(tok);
for (int i = 0; i < l(migrations); i += 2) {
String from = (String) (migrations[i]);
String fromPlusDollar = from + "$";
Object to = migrations[i+1];
String replacement = to instanceof String ? (String) to : dropPrefix("main$", className((Class) to));
int changes = 0;
for (int j = 1; j < n; j += 2) {
String t = tok.get(j);
if (eq(t, from)) {
tok.set(j, replacement);
++changes;
} else if (startsWith(t, fromPlusDollar)) {
tok.set(j, replacement + t.substring(l(from)));
++changes;
}
}
if (changes > 0)
print("migrateClassesInStructureText: Replaced " + n2(changes, "occurrence") + " of " + from + " with " + to);
}
return join(tok);
}
static String migrateClassesInStructureText(String s, Map migrations) {
return migrateClassesInStructureText(s, mapToParams(migrations));
}
static String i(String s, Object... params) {
return tag("i", s, params);
}
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 == '\t')
out.append("\\t");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return c == null ? "null" : new String(c);
}
static String str(char[] c, int offset, int count) {
return new String(c, offset, count);
}
static boolean dynamicObjectIsLoading() {
return isUnstructuring();
}
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(Object... objects) { throw new Fail(objects); }
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 assertInstanceOf(Class type, Object o) {
assertIsInstance(type, o);
}
static void assertInstanceOf(Object o, Class type) {
assertInstanceOf(type, o);
}
static File userDir() {
return new File(userHome());
}
static File userDir(String path) {
return new File(userHome(), path);
}
static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static A assertNotNull(Scorer scorer, String msg, A a) {
if (scorer == null) return assertNotNull(msg, a);
if (a == null) {
print("BAD - " + msg + " is null: " + a);
scorer.add(false);
} else {
print("OK, " + msg + " not null: " + a);
scorer.add(true);
}
return a;
}
static boolean isNaN(double d) {
return Double.isNaN(d);
}
static boolean isNaN(float f) {
return Float.isNaN(f);
}
// 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 getOptDynOnly(((DynamicObject) o), field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static Object get_raw(Object o, String field) { try {
if (o == null) return null;
Field f = get_findField(o.getClass(), field);
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
makeAccessible(f);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static Object get(String field, Object o) {
return get(o, field);
}
static boolean get(BitSet bs, int idx) {
return bs != null && bs.get(idx);
}
static String combinePrintParameters(String s, Object o) {
return (endsWithLetterOrDigit(s) ? s + ": " : s) + o;
}
static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
// this syntax should be removed...
static Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static String getStackTrace(String msg) {
return getStackTrace_noRecord(new Throwable(msg));
}
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 void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll_minimalExceptionHandling(vm_busListeners_live(), msg, arg);
pcallFAll_minimalExceptionHandling(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static Class mc() {
return main.class;
}
static ThreadLocal print_byThread() {
synchronized(print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
// f can return false to suppress regular printing
// call print_raw within f to actually print something
static AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
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(BitSet bs) { return !empty(bs); }
static boolean nempty(Map m) {
return !empty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean nempty(IMultiMap mm) { return mm != null && mm.size() != 0; }
static boolean nempty(Object o) { return !empty(o); }
static boolean nempty(Rect r) { return r != null && r.w != 0 && r.h != 0; }
static boolean nempty(MultiSet ms) { return ms != null && !ms.isEmpty(); }
static boolean nempty(IntSize l) { return l != null && l.size() != 0; }
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(Iterable c) { return c == null || !c.iterator().hasNext(); }
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(BitSet bs) { return bs == null || bs.isEmpty(); }
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(MultiSet ms) { return ms == null || ms.isEmpty(); }
static boolean empty(IMultiMap mm) { return mm == null || mm.size() == 0; }
static boolean empty(File f) { return getFileSize(f) == 0; }
static boolean empty(Rect r) { return !(r != null && r.w != 0 && r.h != 0); }
static boolean empty(Chain c) { return c == null; }
static boolean empty(AppendableChain c) { return c == null; }
static boolean empty(IntSize l) { return l == null || l.size() == 0; }
static String appendColonIfNempty(String s) {
return empty(s) ? "" : s + ": ";
}
static void _handleError(Error e) {
//call(javax(), '_handleError, e);
}
static Map> allFields_cache = weakHashMap();
static Set allFields(Object o) {
if (o == null) return emptySet();
Class _c = _getClass(o);
Set fields = allFields_cache.get(_c);
if (fields == null)
allFields_cache.put(_c, fields = asTreeSet(keys(getOpt_getFieldMap(o))));
return fields;
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static Object getOpt(String field, Object o) {
return getOpt_cached(o, field);
}
static Object getOpt_raw(Object o, String field) { try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null) return null;
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
// access of static fields is not yet optimized
static Object getOpt(Class c, String field) { try {
if (c == null) return null;
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
makeAccessible(f);
return f.get(null);
} catch (Exception __e) { throw rethrow(__e); } }
static Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static int stdHash(Object a, String... fields) {
if (a == null) return 0;
int hash = getClassName(a).hashCode();
for (String field : fields)
hash = boostHashCombine(hash, hashCode(getOpt(a, field)));
return hash;
}
static String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++)
a[i] = it.next();
return a;
}
static String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
static long sysNow() {
ping();
return System.nanoTime()/1000000;
}
static ThreadLocal saveTiming_last = new ThreadLocal();
static void saveTiming(long ms) {
print(ms + " ms");
saveTiming_noPrint(ms);
}
static void saveTiming_noPrint(long ms) {
saveTiming_last.set(ms);
}
static ThreadLocal saveTiming_tl() {
return saveTiming_last;
}
static Object nuObject(String className, Object... args) { try {
return nuObject(classForName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }
// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
ret nuObject(_getClass(realm, className), args);
}*/
static A nuObject(Class c, Object... args) { try {
if (args == null || args.length == 0) return nuObjectWithoutArguments(c); // cached!
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : getDeclaredConstructors_cached(c)) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found"
+ (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static A setAll(A o, Map fields) {
if (fields == null) return o;
for (String field : keys(fields))
set(o, field, fields.get(field));
return o;
}
static A setAll(A o, Object... values) {
//values = expandParams(c.getClass(), values);
failIfOddCount(values);
for (int i = 0; i+1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i+1];
set(o, field, value);
}
return o;
}
static ClassLoader classLoaderForObject(Object o) {
if (o instanceof ClassLoader) return ((ClassLoader) o);
if (o == null) return null;
return _getClass(o).getClassLoader();
}
// Note: This is actually broken. Inner classes must stay with a $ separator
static String classNameToVM(String name) {
return name.replace(".", "$");
}
static List javaTokC(String s) {
if (s == null) return null;
int l = s.length();
ArrayList tok = new ArrayList();
int i = 0;
while (i < l) {
int j = i;
char c, d;
// 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;
}
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // 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));
i = j;
}
return tok;
}
static A popLast(List l) {
return liftLast(l);
}
static List popLast(int n, List l) {
return liftLast(n, l);
}
static String commaCombine(Object... l) {
return joinNemptiesWithComma(flattenCollectionsAndArrays(l));
}
static String stringIf(boolean b, String s) {
return stringIfTrue(b, s);
}
static String stringIf(String s, boolean b) {
return stringIf(b, s);
}
static String actualMCDollar() {
return actualMC().getName() + "$";
}
static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static boolean isJavaXClassName(String s) { return isJavaXClassName(s, "main$"); }
static boolean isJavaXClassName(String s, String mcDollar) {
return startsWithOneOf(s, mcDollar, "loadableUtils.");
}
static void quoteToPrintWriter(String s, PrintWriter out) {
if (s == null) { out.print("null"); return; }
out.print('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"') {
out.print('\\'); out.print(c);
} else if (c == '\r')
out.print("\\r");
else if (c == '\n')
out.print("\\n");
else if (c == '\0')
out.print("\\0");
else
out.print(c);
}
out.print('"');
}
static boolean isSubClassOf(Class a, Class b) {
return isSubclass(a, b);
}
static boolean startsWithDigit(String s) {
return nempty(s) && isDigit(s.charAt(0));
}
static boolean isSyntheticOrAnonymous(Class c) {
return c != null && (c.isSynthetic() || isAnonymousClassName(c.getName()));
}
// This is a bit rough... finds static and non-static methods.
static Method findMethodNamed(Object obj, String method) {
if (obj == null) return null;
if (obj instanceof Class)
return findMethodNamed((Class) obj, method);
return findMethodNamed(obj.getClass(), method);
}
static Method findMethodNamed(Class c, String method) {
while (c != null) {
for (Method m : c.getDeclaredMethods())
if (m.getName().equals(method)) {
makeAccessible(m);
return m;
}
c = c.getSuperclass();
}
return null;
}
// keeps package names for dynamic code (package dyn.*)
static String shortDynClassNameForStructure(Object o) {
if (o instanceof DynamicObject && ((DynamicObject) o).className != null)
return ((DynamicObject) o).className;
if (o == null) return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return name.startsWith("dyn.") ? classNameToVM(name) : shortenClassName(name);
}
static boolean isPersistableClass(Class c) {
String name = c.getName();
if (isSubtypeOf(c, TransientObject.class)) return false;
if (isAnonymousClassName(name)) return false;
if (isBoxedType(c)) return true;
if (isArrayType(c)) return true;
if (c == Class.class || c == String.class || c == File.class || c == Color.class) return true;
if (name.startsWith("java.util.Collections$Synchronized")) return true;
if (hasThisDollarFields(c))
return hasSingleArgumentConstructor(c);
else
return getDefaultConstructor(c) != null;
}
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 byte last(byte[] a) {
return l(a) != 0 ? a[l(a)-1] : 0;
}
static int last(int[] a) {
return l(a) != 0 ? a[l(a)-1] : 0;
}
static long last(long[] 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;
if (l instanceof List) return (A) last((List) l);
if (l instanceof SortedSet) return (A) last((SortedSet) l);
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 A last(ReverseChain l) {
return l == null ? null : l.element;
}
static A last(CompactLinkedHashSet set) {
return set == null ? null : set.last();
}
static A printStackTrace(A e) {
// we go to system.out now - system.err is nonsense
if (e != null) print(getStackTrace(e));
return e;
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static Constructor getDefaultConstructor(Class c) {
if (c != null)
for (Constructor m : getDeclaredConstructors_cached(c))
if (empty(m.getParameterTypes()))
return m;
return null;
}
static Object invokeConstructor(Constructor m, Object... args) { try {
makeAccessible(m);
return m.newInstance(args);
} catch (Exception __e) { throw rethrow(__e); } }
static int countDots(String s) {
int n = l(s), count = 0;
for (int i = 0; i < n; i++) if (s.charAt(i) == '.') ++count;
return count;
}
static boolean isCIMap_gen(Map map) {
return map instanceof TreeMap && className(((TreeMap) map).comparator()).contains("CIComp");
}
static Map cloneMap(Map map) {
if (map == null) return new HashMap();
// assume mutex is equal to map
synchronized(map) {
return map instanceof TreeMap ? new TreeMap((TreeMap) map) // copies comparator
: map instanceof LinkedHashMap ? new LinkedHashMap(map)
: new HashMap(map);
}
}
static List cloneMap(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : cloneList(l))
x.add(f.get(o));
return x;
}
// Use like this: renderVars(+x, +y)
// Or like this: renderVars SomeID(+x, +y)
static String renderVars(Object... params) {
return renderVars_str(params);
}
static Pair mapEntryToPair(Map.Entry e) {
return e == null ? null : pair(e.getKey(), e.getValue());
}
static boolean isCISet_gen(Iterable l) {
return l instanceof TreeSet && className(((TreeSet) l).comparator()).contains("CIComp");
}
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 Object invokeMethod(Method m, Object o, Object... args) { try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) { throw rethrow(__e); } }
static String quoteCharacter(char c) {
if (c == '\'') return "'\\''";
if (c == '\\') return "'\\\\'";
if (c == '\r') return "'\\r'";
if (c == '\n') return "'\\n'";
if (c == '\t') return "'\\t'";
return "'" + c + "'";
}
public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}
public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len*2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs+i]);
stringBuilder.append(s.substring(s.length()-2, s.length()));
}
return stringBuilder.toString();
}
static String boolArrayToHex(boolean[] a) {
return bytesToHex(boolArrayToBytes(a));
}
static String substring(String s, int x) {
return substring(s, x, strL(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
int n = s.length();
if (y < x) y = x;
if (y > n) y = n;
if (x >= y) return "";
return s.substring(x, y);
}
// convenience method for quickly dropping a prefix
static String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
static String shortArrayToHex_bigEndian(short[] a) {
return bytesToHex(byteArrayFromShorts_bigEndian(a));
}
static String longArrayToHex_bigEndian(long[] a) {
return bytesToHex(byteArrayFromLongs_bigEndian(a));
}
static Pair arrayTypeAndDimensions(Object o) {
return arrayTypeAndDimensions(_getClass(o));
}
static Pair arrayTypeAndDimensions(Class c) {
if (c == null || !c.isArray()) return null;
Class elem = c.getComponentType();
if (elem.isArray())
return mapPairB(arrayTypeAndDimensions(elem), dim -> dim+1);
return pair(elem, 1);
}
static Iterator emptyIterator() {
return Collections.emptyIterator();
}
static int stdcompare(Number a, Number b) {
return cmp(a, b);
}
static int stdcompare(String a, String b) {
return cmp(a, b);
}
static int stdcompare(long a, long b) {
return a < b ? -1 : a > b ? 1 : 0;
}
static int stdcompare(Object a, Object b) {
return cmp(a, b);
}
static Map getDeclaredFields_cache = newDangerousWeakHashMap();
static Field[] getDeclaredFields_cached(Class c) {
Field[] fields;
synchronized(getDeclaredFields_cache) {
fields = getDeclaredFields_cache.get(c);
if (fields == null) {
getDeclaredFields_cache.put(c, fields = c.getDeclaredFields());
for (Field f : fields)
makeAccessible(f);
}
}
return fields;
}
static Object fieldGet(Field f, Object o) { try {
return f == null ? null : f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
static Method findInstanceMethod(Class c, String method, Object... args) {
while (c != null) {
for (Method m : c.getDeclaredMethods())
if (m.getName().equals(method) && findMethod_checkArgs(m, args, false))
return m;
c = c.getSuperclass();
}
return null;
}
// unclear semantics as to whether return null on null
static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static ArrayList asList(char[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (var i : a) l.add(i);
return l;
}
static ArrayList asList(byte[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (var i : a) l.add(i);
return l;
}
static ArrayList asList(int[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(long[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static ArrayList asList(float[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static ArrayList asList(double[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static ArrayList asList(short[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (short i : a) l.add(i);
return l;
}
static ArrayList asList(Iterator it) {
ArrayList l = new ArrayList();
if (it != null)
while (it.hasNext())
l.add(it.next());
return l;
}
// disambiguation
static ArrayList asList(IterableIterator s) {
return asList((Iterator) s);
}
static ArrayList asList(Iterable s) {
if (s instanceof ArrayList) return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null) while ((a = p.next()) != null)
l.add(a);
return l;
}
static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
static ArrayList asList(ReverseChain c) {
return c == null ? emptyList() : c.toList();
}
static List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
static Set fieldObjectsInFieldOrder(Class c, Set fields) {
try {
var byName = mapToKey(f -> f.getName(), fields);
LinkedHashSet out = new LinkedHashSet();
for (String name : unnullForIteration(getFieldOrder(c))) {
Field f = byName.get(name);
if (f != null) {
byName.remove(name);
out.add(f);
}
}
addAll(out, fields);
return out;
} catch (Throwable __0) { printStackTrace(__0);
return fields;
}
}
static Object getOptDynOnly(DynamicObject o, String field) {
if (o == null || o.fieldValues == null) return null;
return o.fieldValues.get(field);
}
static int identityHashCode(Object o) {
return System.identityHashCode(o);
}
static Map putAll(Map a, Map extends A,? extends B> b) {
if (a != null && b != null) a.putAll(b);
return a;
}
static MultiMap putAll(MultiMap a, Map extends A,? extends B> b) {
if (a != null) a.putAll((Map) b);
return a;
}
static Map putAll(Map a, Object... b) {
if (a != null)
litmap_impl(a, b);
return a;
}
static String quoted(Object o) {
return quote(o);
}
static String quoted(String s) {
return quote(s);
}
static ThreadLocal assertVerbose_value = new ThreadLocal();
static void assertVerbose(boolean b) {
assertVerbose_value.set(b);
}
static boolean assertVerbose() { return isTrue(assertVerbose_value.get()); }
static String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
static Map nullIfEmpty(Map map) {
return isEmpty(map) ? null : map;
}
static List nullIfEmpty(List l) {
return isEmpty(l) ? null : l;
}
static Producer javaTokC_noMLS_iterator(final String s) {
return javaTokC_noMLS_iterator(s, 0);
}
static Producer javaTokC_noMLS_iterator(final String s, final int startIndex) {
return new Producer() {
final int l = s.length();
int i = startIndex;
public String next() {
if (i >= l) return null;
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;
}
i = j;
if (i >= l) return null;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
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
++j;
String t = quickSubstring(s, i, j);
i = j;
return t;
}
};
}
static Producer javaTokC_noMLS_onReader(final BufferedReader r) {
final class X implements Producer {
StringBuilder buf = new StringBuilder(); // stores from "i"
char c, d, e = 'x'; // just not '\0'
X() {
// fill c, d and e
nc();
nc();
nc();
}
// get next character(s) into c, d and e
void nc() { try {
c = d;
d = e;
if (e == '\0') return;
int i = r.read();
e = i < 0 ? '\0'
: i == '\0' ? '_' // shouldn't happen anymore
: (char) i;
} catch (Exception __e) { throw rethrow(__e); } }
void ncSave() {
if (c != '\0') {
buf.append(c);
nc();
}
}
public String next() {
// scan for whitespace
while (c != '\0') {
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
nc();
else if (c == '/' && d == '*') {
do nc(); while (c != '\0' && !(c == '*' && d == '/'));
nc(); nc();
} else if (c == '/' && d == '/') {
do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0);
} else
break;
}
if (c == '\0') return null;
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
ncSave();
while (c != '\0') {
if (c == opener || c == '\n') { // end at \n to not propagate unclosed string literal errors
ncSave();
break;
} else if (c == '\\') {
ncSave();
ncSave();
} else
ncSave();
}
} else if (Character.isJavaIdentifierStart(c))
do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\''); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ncSave(); while (Character.isDigit(c));
if (c == 'L') ncSave(); // Long constants like 1L
} else
ncSave();
String t = buf.toString();
buf.setLength(0);
return t;
}
}
return new X();
}
static void pcallFail(Throwable e) {
pcallPolicyForThread().handlePcallFail(e);
}
static void pcallFail(String msg) {
pcallFail(new Throwable(msg));
}
static BigInteger parseBigInt(String s) {
return new BigInteger(s);
}
static double parseDouble(String s) {
return empty(s) ? 0.0 : Double.parseDouble(s);
}
static float parseFloat(String s) {
return Float.parseFloat(s);
}
static int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static int parseInt(char c) {
return Integer.parseInt(str(c));
}
static boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++)
if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static String trivialUnquote(String s) {
return dropPrefixSuffix("\"", s);
}
static short[] shortArrayFromBytes(byte[] a) {
return shortArrayFromBytes(a, 0, l(a));
}
static short[] shortArrayFromBytes(byte[] a, int from, int to) {
short[] b = new short[(to-from)/2];
for (int i = 0; i < b.length; i++)
b[i] = shortFromBytes(a, from+i*2);
return b;
}
static byte[] hexToBytes(String s) {
if (odd(l(s))) throw fail("Hex string has odd length: " + quote(shorten(10, s)));
int n = l(s) / 2;
byte[] bytes = new byte[n];
for (int i = 0; i < n; i++) {
int a = parseHexChar(s.charAt(i*2));
int b = parseHexChar(s.charAt(i*2+1));
if (a < 0 || b < 0)
throw fail("Bad hex byte: " + quote(substring(s, i*2, i*2+2)) + " at " + i*2 + "/" + l(s));
bytes[i] = (byte) ((a << 4) | b);
}
return bytes;
}
static long[] longArrayFromBytes(byte[] a) {
return longArrayFromBytes(a, 0, l(a));
}
static long[] longArrayFromBytes(byte[] a, int from, int to) {
long[] b = new long[(to-from)/8];
for (int i = 0; i < b.length; i++)
b[i] = longFromBytes_bigEndian(a, from+i*8);
return b;
}
static HashMap findClass_fullName_cache = new HashMap();
// returns null on not found
// this is the simple version that is not case-tolerant
static Class findClass_fullName(String name) {
synchronized(findClass_fullName_cache) {
if (findClass_fullName_cache.containsKey(name))
return findClass_fullName_cache.get(name);
Class c;
try {
c = Class.forName(name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_fullName_cache.put(name, c);
return c;
}
}
static String unquoteUsingCharArray(String s, char[] buf) {
if (s == null) return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i+1, s.length()-i-1);
}
}
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length()-1 : s.length();
if (l > buf.length) return unquote(s); // fallback
int n = 0;
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
buf[n++] = (char) Integer.parseInt(code, 8);
continue;
}
switch (nextChar) {
case '\"': ch = '\"'; break;
case '\\': ch = '\\'; break;
case 'b': ch = '\b'; break;
case 'f': ch = '\f'; break;
case 'n': ch = '\n'; break;
case 'r': ch = '\r'; break;
case 't': ch = '\t'; break;
case '\'': ch = '\''; break;
// Hex Unicode: u????
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + s.charAt(i + 2) + s.charAt(i + 3)
+ s.charAt(i + 4) + s.charAt(i + 5), 16);
char[] x = Character.toChars(code);
int lx = x.length;
for (int j = 0; j < lx; j++)
buf[n++] = x[j];
i += 5;
continue;
default:
ch = nextChar; // added by Stefan
}
i++;
}
buf[n++] = ch;
}
return new String(buf, 0, n);
}
}
return s; // not quoted - return original
}
static boolean structure_isMarker(String s, int i, int j) {
if (i >= j) return false;
if (s.charAt(i) != 'm') return false;
++i;
while (i < j) {
char c = s.charAt(i);
if (c < '0' || c > '9') return false;
++i;
}
return true;
}
static String internIfLongerThan(String s, int l) {
return s == null ? null : l(s) >= l ? intern(s) : s;
}
static String unquote(String s) {
if (s == null) return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i+1, s.length()-i-1);
}
}
return unquoteSingleOrDoubleQuotes(s);
}
static char unquoteCharacter(String s) {
assertTrue(s.startsWith("'") && s.length() > 1);
return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length()-1 : s.length()) + "\"").charAt(0);
}
static boolean isLongConstant(String s) {
if (!s.endsWith("L")) return false;
s = s.substring(0, l(s)-1);
return isInteger(s);
}
static long parseLong(String s) {
if (empty(s)) return 0;
return Long.parseLong(dropSuffix("L", s));
}
static long parseLong(Object s) {
return Long.parseLong((String) s);
}
static boolean isInteger(String s) {
int n = l(s);
if (n == 0) return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n) return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9') return false;
++i;
}
return true;
}
static boolean warn_on = true;
static ThreadLocal> warn_warnings = new ThreadLocal();
static void warn(String s) {
if (warn_on)
print("Warning: " + s);
}
static void warn(String s, List warnings) {
warn(s);
if (warnings != null)
warnings.add(s);
addToCollection(warn_warnings.get(), s);
}
static TreeMap ciMap() {
return caseInsensitiveMap();
}
static List parseList(String s) {
return (List) safeUnstructure(s);
}
static List synchroLinkedList() {
return synchroList(new LinkedList ());
}
static NavigableMap synchroNavigableMap(NavigableMap map) {
return new SynchronizedNavigableMap(map);
}
static SortedMap synchroSortedMap(SortedMap map) {
return new SynchronizedSortedMap(map);
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return new SynchronizedMap(map);
}
static boolean[] boolArrayFromBytes(byte[] a, int n) {
boolean[] b = new boolean[n];
int m = min(n, l(a)*8);
for (int i = 0; i < m; i++)
b[i] = (a[i/8] & 1 << (i & 7)) != 0;
return b;
}
static Object call(Object o) {
return callF(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) {
//ret call_cached(o, method, args);
return call_withVarargs(o, method, args);
}
static String assertIdentifier(String s) {
return assertIsIdentifier(s);
}
static String assertIdentifier(String msg, String s) {
return assertIsIdentifier(msg, s);
}
static boolean isAbstract(Class c) {
return (c.getModifiers() & Modifier.ABSTRACT) != 0;
}
static boolean isAbstract(Method m) {
return (m.getModifiers() & Modifier.ABSTRACT) != 0;
}
// Use like this: printVars_str(+x, +y);
// Or: printVars("bla", +x);
// Or: printVars bla(+x);
static void printVars_str(Object... params) {
print(renderVars_str(params));
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b)) return false;
if (m != null) m.m = new String[] {substring(a, strL(b))};
return true;
}
static boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a)) return false;
for (int i = 0; i < listL(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static Constructor nuStubInnerObject_findConstructor(Class c) { return nuStubInnerObject_findConstructor(c, null); }
static Constructor nuStubInnerObject_findConstructor(Class c, Object classFinder) { try {
Class outerType = getOuterClass(c, classFinder);
Constructor m = c.getDeclaredConstructor(outerType);
makeAccessible(m);
return m;
} catch (Exception __e) { throw rethrow(__e); } }
static Map nuEmptyObject_cache = newDangerousWeakHashMap();
static A nuEmptyObject(Class c) { try {
Constructor ctr;
synchronized(nuEmptyObject_cache) {
ctr = nuEmptyObject_cache.get(c);
if (ctr == null) {
nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
makeAccessible(ctr);
}
}
try {
return (A) ctr.newInstance();
} catch (InstantiationException e) {
if (empty(e.getMessage()))
if ((c.getModifiers() & Modifier.ABSTRACT) != 0)
throw fail("Can't instantiate abstract class " + className(c), e);
else
throw fail("Can't instantiate " + className(c), e);
else throw rethrow(e);
}
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuEmptyObject_findConstructor(Class c) {
for (Constructor m : getDeclaredConstructors_cached(c))
if (m.getParameterTypes().length == 0)
return m;
throw fail("No default constructor declared in " + c.getName());
}
static void setOptAllDyn_pcall(DynamicObject o, Map fields) {
if (fields == null || o == null) return;
HashMap fieldMap = instanceFieldsMap(o);
for (Map.Entry e : fields.entrySet()) { try {
String field = e.getKey();
Object val = e.getValue();
Field f = fieldMap.get(field);
if (f != null)
smartSet(f, o, val);
else {
dynamicObject_setRawFieldValue(o, intern(field), val);
}
} catch (Throwable __e) { pcallFail(__e); }}
}
static void setOptAll_pcall(Object o, Map fields) {
if (fields == null) return;
for (String field : keys(fields))
try { setOpt(o, field, fields.get(field)); } catch (Throwable __e) { print(exceptionToStringShort(__e)); }
}
static void setOptAll_pcall(Object o, Object... values) {
//values = expandParams(c.getClass(), values);
warnIfOddCount(values);
for (int i = 0; i+1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i+1];
try { setOpt(o, field, value); } catch (Throwable __e) { print(exceptionToStringShort(__e)); }
}
}
static void fixOuterRefs(Object o) { try {
if (o == null) return;
Field[] l = thisDollarOneFields(o.getClass());
if (l.length <= 1) return;
Object father = null;
for (Field f : l) {
father = f.get(o);
if (father != null) break;
}
if (father == null) return;
for (Field f : l)
f.set(o, father);
} catch (Exception __e) { throw rethrow(__e); } }
static void setDynObjectValue(DynamicObject o, String field, Object value) {
dynamicObject_setRawFieldValue(o, field, value);
}
static String intern(String s) {
return fastIntern(s);
}
static void pcallOpt_noArgs(Object o, String method) {
try { callOpt_noArgs(o, method); } catch (Throwable __e) { pcallFail(__e); }
}
static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static List subList(int startIndex, List l) {
return subList(l, startIndex);
}
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 RuntimeException todo() {
throw new RuntimeException("TODO");
}
static RuntimeException todo(Object msg) {
throw new RuntimeException("TODO: " + msg);
}
static Object newMultiDimensionalOuterArray(Class elementType, int dimensions, int length) {
int[] dims = new int[dimensions];
dims[0] = length;
return Array.newInstance(elementType, dims);
}
static int[] toIntArray(Collection l) {
int[] a = new int[l(l)];
int i = 0;
if (a.length != 0) for (int x : l)
a[i++] = x;
return a;
}
static double[] toDoubleArray(Collection l) {
double[] a = new double[l(l)];
int i = 0;
if (a.length != 0) for (double x : l)
a[i++] = x;
return a;
}
static double[] toDoubleArray(float... l) {
double[] a = new double[l(l)];
for (int i = 0; i < a.length; i++)
a[i] = l[i];
return a;
}
static double[] toDoubleArray(int... l) {
double[] a = new double[l(l)];
for (int i = 0; i < a.length; i++)
a[i] = l[i];
return a;
}
static float[] toFloatArray(List l) {
float[] a = new float[l(l)];
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
return a;
}
static float[] toFloatArray(double[] l) {
float[] a = new float[l(l)];
for (int i = 0; i < a.length; i++)
a[i] = (float) l[i];
return a;
}
static void dynamicObject_setRawFieldValue(DynamicObject o, Object key, Object value) {
if (o == null) return;
// double sync, but should be OK here because of locking order o > o.fieldValues
synchronized(o) {
o.fieldValues = syncMapPut2_createLinkedHashMap((LinkedHashMap) o.fieldValues, key, value);
}
}
static TreeSet ciSet() {
return caseInsensitiveSet();
}
// DIFFERENCES to jfind: always ignores case, doesn't recognize etc
// You probably want jmatch2
static boolean jmatch(String pat, String s) {
return jmatch(pat, s, null);
}
static boolean jmatch(String pat, String s, Matches matches) {
if (s == null) return false;
return jmatch(pat, javaTok(s), matches);
}
static boolean jmatch(String pat, List toks) {
return jmatch(pat, toks, null);
}
static boolean jmatch(String pat, List toks, Matches matches) {
List tokpat = javaTok(pat);
String[] m = match2(tokpat, toks);
//print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
if (m == null)
return false;
else {
if (matches != null) matches.m = m;
return true;
}
}
static AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
static AutoCloseable tempSetTL(BetterThreadLocal tl, A a) {
return tempSetThreadLocalIfNecessary(tl, a);
}
static ThreadLocal DynamicObject_loading = or((ThreadLocal) get(getClass("x30_pkg.x30_util"), "DynamicObject_loading"), new ThreadLocal());
static ThreadLocal dynamicObjectIsLoading_threadLocal() {
return DynamicObject_loading;
}
static void _close(AutoCloseable c) {
if (c != null) try {
c.close();
} catch (Throwable e) {
// Some classes stupidly throw an exception on double-closing
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else throw rethrow(e);
}
}
static NavigableMap synchroTreeMap() {
return synchroNavigableMap(new TreeMap());
}
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
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 CharSequence subCharSequence(CharSequence s, int x) {
return subCharSequence(s, x, s == null ? 0 : s.length());
}
static CharSequence subCharSequence(CharSequence s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
if (x >= s.length()) return "";
if (y < x) y = x;
if (y > s.length()) y = s.length();
return s.subSequence(x, y);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x) x = d;
return x;
}
static > A min(A a, A b) {
return cmp(a, b) <= 0 ? a : b;
}
static int iteratorCount_int_close(Iterator i) { try {
int n = 0;
if (i != null) while (i.hasNext()) { i.next(); ++n; }
if (i instanceof AutoCloseable) ((AutoCloseable) i).close();
return n;
} catch (Exception __e) { throw rethrow(__e); } }
static String joinNemptiesWithColon(String... strings) {
return joinNempties(": ", strings);
}
static String joinNemptiesWithColon(Collection strings) {
return joinNempties(": ", strings);
}
static int identityHash(Object o) {
return identityHashCode(o);
}
static Set> entrySet(Map map) {
return _entrySet(map);
}
static A firstThat(Iterable l, IF1 pred) {
for (A a : unnullForIteration(l))
if (pred.get(a))
return a;
return null;
}
static A firstThat(A[] l, IF1 pred) {
for (A a : unnullForIteration(l))
if (pred.get(a))
return a;
return null;
}
static A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static A firstThat(IF1 pred, A[] l) {
return firstThat(l, pred);
}
static Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
// initFunction: voidfunc(Map) - is called initially, and after clearing the map
static Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != l(args)) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive()
: isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
static Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
// Note: The error reporting only works with Java VM option --illegal-access=deny
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static Object defaultDefaultClassFinder() {
return new F1() {
public Class get(String name) {
// Fix some buggy concepts files out there
name = replacePrefix("main$main$", "main$", name);
Class c = get2(name);
return c;
}
Class get2(String name) {
// special invocation to find main class irrelevant of name
if (eq(name, "")) return mc();
{ Class c = findClass_fullName(name); if (c != null) return c; }
if (startsWithAny(name, "loadableUtils.utils$", "main$", mcDollar()))
for (String pkg : ll("loadableUtils.utils$", mcDollar())) {
String newName = pkg + afterDollar(name);
{ Class c = findClass_fullName(newName); if (c != null) return c; }
}
return null;
}
};
}
static HashMap findClass_cache = new HashMap();
// currently finds only inner classes of class "main"
// returns null on not found
// this is the simple version that is not case-tolerant
static Class findClass(String name) {
synchronized(findClass_cache) {
if (findClass_cache.containsKey(name))
return findClass_cache.get(name);
if (!isJavaIdentifier(name)) return null;
Class c;
try {
c = Class.forName("main$" + name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_cache.put(name, c);
return c;
}
}
static String str_shorten(Object o) {
return shorten_str(o);
}
static String str_shorten(Object o, int max) {
return shorten_str(o, max);
}
static String str_shorten(int max, Object o) {
return shorten_str(max, o);
}
static Object derefRef(Object o) {
if (o instanceof Concept.Ref) o = ((Concept.Ref) o).get();
return o;
}
static A derefRef(Concept.Ref r) {
return r == null ? null : r.get();
}
static List lambdaMap(IF1 f, Iterable l) {
return map(l, f);
}
static List lambdaMap(IF1 f, A[] l) {
return map(l, f);
}
static void setOptAllDyn(DynamicObject o, Map fields) {
if (fields == null) return;
HashMap fieldMap = instanceFieldsMap(o);
for (Map.Entry e : fields.entrySet()) {
String field = e.getKey();
Object val = e.getValue();
boolean has = fieldMap.containsKey(field);
if (has)
setOpt(o, field, val);
else {
dynamicObject_setRawFieldValue(o, field, val);
}
}
}
static Map paramsToMap(Object... params) {
int n = l(params);
if (l(params) == 1 && params[0] instanceof Map) return (Map) params[0];
LinkedHashMap map = new LinkedHashMap();
for (int i = 0; i+1 < n; i += 2)
mapPut(map, params[i], params[i+1]);
return map;
}
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 fulltag(String tag) {
return hfulltag(tag);
}
static String fulltag(String tag, Object contents, Object... params) {
return hfulltag(tag, contents, params);
}
static List javaTokForStructure(String s) {
return javaTok_noMLS(s);
}
static String n2(long l) { return formatWithThousands(l); }
static String n2(AtomicLong l) { return n2(l.get()); }
static String n2(Collection l) { return n2(l(l)); }
static String n2(Map map) { return n2(l(map)); }
static String n2_getPlural(String singular) {
//ret singular + "s";
return plural(singular);
}
static String n2(double l, String singular) {
return empty(singular) ? str(l) : n2(l, singular, n2_getPlural(singular));
}
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 empty(singular) ? n2(l) : n_fancy2(l, singular, n2_getPlural(singular));
}
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(long[] a, String singular) { return n2(l(a), 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 n2(MultiSet ms, String singular) { return n2(ms, singular, n2_getPlural(singular)); }
static String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static String n2(IMultiMap mm, String singular) { return n2(mm, singular, n2_getPlural(singular)); }
static String n2(IMultiMap mm, String singular, String plural) {
return n_fancy2(l(mm), singular, plural);
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1) return strOrEmpty(first((Collection) strings));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(strOrEmpty(i.next()));
while (i.hasNext())
buf.append(glue).append(strOrEmpty(i.next()));
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(String glue, Object... 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 Object[] mapToParams(Map map) {
return mapToObjectArray(map);
}
static String tag(String tag) {
return htag(tag);
}
static String tag(String tag, Object contents, Object... params) {
return htag(tag, str(contents), params);
}
static String tag(String tag, StringBuilder contents, Object... params) {
return htag(tag, contents, params);
}
static String tag(String tag, StringBuffer contents, Object... params) {
return htag(tag, contents, params);
}
static boolean isUnstructuring() {
return isTrue(getTL(dynamicObjectIsLoading_threadLocal()));
}
static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static void assertIsInstance(Class type, Object o) {
if (!isInstance(type, o))
throw fail(_getClass(o) + " is not a subclass of " + type);
}
static void assertIsInstance(Object o, Class type) {
assertIsInstance(type, o);
}
static String _userHome;
static String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
static File userHome(String path) {
return new File(userDir(), path);
}
static Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1));
}
// legacy mode
//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();
// ignore pingSource if not PingV3
static boolean ping(PingSource pingSource) { return ping(); }
// always returns true
static boolean ping() {
//ifdef useNewPing
newPing();
//endifdef
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 A or(A a, A b) {
return a != null ? a : b;
}
// PersistableThrowable doesn't hold GC-disturbing class references in backtrace
static volatile PersistableThrowable lastException_lastException;
static PersistableThrowable lastException() {
return lastException_lastException;
}
static void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }
static String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url))) return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=");
}
static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
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 int indexOf(Iterable l, A a) {
if (l == null) return -1;
int i = 0;
for (A x : l) {
if (eq(x, a))
return i;
i++;
}
return -1;
}
static void rotateStringBuffer(StringBuffer buf, int max) { try {
if (buf == null) return;
synchronized(buf) {
if (buf.length() <= max) return;
try {
int newLength = max/2;
int ofs = buf.length()-newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) { throw rethrow(__e); } }
static void rotateStringBuilder(StringBuilder buf, int max) { try {
if (buf == null) return;
synchronized(buf) {
if (buf.length() <= max) return;
try {
int newLength = max/2;
int ofs = buf.length()-newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) { throw rethrow(__e); } }
static Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null
: l(args) == 1 ? args[0]
: args;
}
static void pcallFAll_minimalExceptionHandling(Collection l, Object... args) {
if (l != null) for (Object f : cloneList(l)) { ping(); pcallF_minimalExceptionHandling(f, args); }
}
static void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) {
while (it.hasNext()) { ping(); pcallF_minimalExceptionHandling(it.next(), args); }
}
static Set vm_busListeners_live_cache;
static Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache;}
static Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static Map vm_busListenersByMessage_live_cache;
static Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache;}
static Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null) return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }};
}
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 Map weakHashMap() {
return newWeakHashMap();
}
static Set emptySet() {
return new HashSet();
}
static TreeSet asTreeSet(Collection set) {
return set == null ? null : set instanceof TreeSet ? (TreeSet) set : new TreeSet(set);
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
// convenience shortcut for keys_gen
static Set keys(Object map) {
return keys((Map) map);
}
static Set keys(MultiSet ms) {
return ms.keySet();
}
static Set keys(IMultiMap mm) {
return mm.keySet();
}
//static final Map> getOpt_cache = newDangerousWeakHashMap(f getOpt_special_init);
static class getOpt_Map extends WeakHashMap {
getOpt_Map() {
if (getOpt_special == null) getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
//print("getOpt clear");
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final Map> getOpt_cache =
_registerDangerousWeakMap(synchroMap(new getOpt_Map()));
static HashMap getOpt_special; // just a marker
/*static void getOpt_special_init(Map map) {
map.put(Class.class, getOpt_special);
map.put(S.class, getOpt_special);
}*/
static Map getOpt_getFieldMap(Object o) {
Class c = _getClass(o);
HashMap map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
return map;
}
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Map map = getOpt_getFieldMap(o);
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
/*if (o instanceof S)
ret getOpt(getBot((S) o), field);*/
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null) return f.get(o);
if (o instanceof DynamicObject)
return syncMapGet2(((DynamicObject) o).fieldValues, field);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
// used internally - we are in synchronized block
static HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
if (!reflection_classesNotToScan().contains(c.getName())) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
makeAccessible(f);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
}
if (getOpt_cache != null) getOpt_cache.put(c, map);
return map;
}
static int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >>> 2));
// OLD (changed) 2022/3/10: ret a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}
static int hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static int hashCode(long l) {
return Long.hashCode(l);
}
static int hashCode(double d) {
return Double.hashCode(d);
}
static Map classForName_cache = synchroHashMap();
static Class classForName(String name) { return classForName(name, null); }
static Class classForName(String name, Object classFinder) {
// first clause is when we're in class init
if (classForName_cache == null || classFinder != null)
return classForName_uncached(name, classFinder);
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = classForName_uncached(name, null));
return c;
}
static Class classForName_uncached(String name, Object classFinder) { try {
if (classFinder != null) return (Class) callF(classFinder, name);
return Class.forName(name);
} catch (Exception __e) { throw rethrow(__e); } }
static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static Object nuObjectWithoutArguments(String className) { try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) { throw rethrow(__e); } }
static A nuObjectWithoutArguments(Class c) { try {
if (nuObjectWithoutArguments_cache == null)
// in class init
return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
Constructor m = nuObjectWithoutArguments_cache.get(c);
if (m == null)
nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
return (A) m.newInstance();
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : getDeclaredConstructors_cached(c))
if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
// TODO: convert to regularly cleared normal map
static Map getDeclaredConstructors_cached_cache = newDangerousWeakHashMap();
static Constructor[] getDeclaredConstructors_cached(Class c) {
Constructor[] ctors;
synchronized(getDeclaredConstructors_cached_cache) {
ctors = getDeclaredConstructors_cached_cache.get(c);
if (ctors == null) {
getDeclaredConstructors_cached_cache.put(c, ctors = c.getDeclaredConstructors());
for (var ctor : ctors)
makeAccessible(ctor);
}
}
return ctors;
}
static List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class) return arg instanceof Boolean;
if (type == int.class) return arg instanceof Integer;
if (type == long.class) return arg instanceof Long;
if (type == float.class) return arg instanceof Float;
if (type == short.class) return arg instanceof Short;
if (type == char.class) return arg instanceof Character;
if (type == byte.class) return arg instanceof Byte;
if (type == double.class) return arg instanceof Double;
return type.isInstance(arg);
}
static A set(A o, String field, Object value) {
if (o == null) return null;
if (o instanceof Class) set((Class) o, field, value);
else try {
Field f = set_findField(o.getClass(), field);
makeAccessible(f);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
static void set(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = set_findStaticField(c, field);
makeAccessible(f);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static void set(BitSet bs, int idx) {
{ if (bs != null) bs.set(idx); }
}
static void failIfOddCount(Object... list) {
if (odd(l(list)))
throw fail("Odd list size: " + list);
}
static String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
static A liftLast(List l) {
if (empty(l)) return null;
int i = l(l)-1;
A a = l.get(i);
l.remove(i);
return a;
}
static List liftLast(int n, List l) {
int i = l(l)-n;
List part = cloneSubList(l, i);
removeSubList(l, i);
return part;
}
static String joinNemptiesWithComma(Object... strings) {
return joinNempties(", ", strings);
}
static String joinNemptiesWithComma(Iterable strings) {
return joinNempties(", ", strings);
}
static List flattenCollectionsAndArrays(Iterable a) {
List l = new ArrayList();
for (Object x : a)
if (x instanceof Collection)
l.addAll(flattenCollectionsAndArrays((Collection) x));
else if (x instanceof Object[])
l.addAll(flattenCollectionsAndArrays(asList((Object[]) x)));
else
l.add(x);
return l;
}
static List flattenCollectionsAndArrays(Object... whatever) {
return flattenCollectionsAndArrays(ll(whatever));
}
static String stringIfTrue(boolean b, String s) {
return b ? s : "";
}
static Class actualMC() {
return or((Class) realMC(), mc());
}
static boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x)) return true; return false;
}
static boolean startsWithOneOf(String s, Matches m, String... l) {
for (String x : l) if (startsWith(s, x, m)) return true; return false;
}
static boolean isSubclass(Class a, Class b) {
return a != null && b != null && b.isAssignableFrom(a);
}
static boolean isDigit(char c) {
return Character.isDigit(c);
}
static boolean isAnonymousClassName(String s) {
for (int i = 0; i < l(s); i++)
if (s.charAt(i) == '$' && Character.isDigit(s.charAt(i+1)))
return true;
return false;
}
static boolean isSubtypeOf(Class a, Class b) {
return a != null && b != null && b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static boolean isBoxedType(Class type) {
return type == Boolean.class
|| type == Integer.class
|| type == Long.class
|| type == Float.class
|| type == Short.class
|| type == Character.class
|| type == Byte.class
|| type == Double.class;
}
static boolean isArrayType(Class type) {
return type != null && type.isArray();
}
static boolean hasThisDollarFields(Object o) {
Matches m = new Matches();
for (var f : allFieldObjects_dontMakeAccessible(o))
if (startsWith(f.getName(), "this$", m) && isInteger(m.rest()))
return true;
return false;
}
static boolean hasSingleArgumentConstructor(Class c) {
if (c != null)
for (Constructor m : getDeclaredConstructors_cached(c))
if (l(m.getParameterTypes()) == 1)
return true;
return false;
}
static Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
// Use like this: renderVars(+x, +y)
// Or like this: renderVars("bla", +x, +y)
static String renderVars_str(Object... params) {
List l = new ArrayList();
int i = 0;
if (odd(l(params))) {
l.add(strOrNull(first(params)));
++i;
}
for (; i+1 < l(params); i += 2)
l.add(params[i] + "=" + params[i+1]);
return trim(joinWithComma(l));
}
// TODO: JDK 17!! ?? No! Yes? Yes!!
static Object collectionMutex(List l) {
return l;
}
static Object collectionMutex(Object o) {
if (o instanceof List) return o;
// TODO: actually use our own maps so we can get the mutex properly
String c = className(o);
return o;
}
static Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static String joinWithSpace(Iterable c) {
return join(" ", c);
}
static String joinWithSpace(Object... c) {
return join(" ", c);
}
static List classNames(Collection l) {
return getClassNames(l);
}
static List classNames(Object[] l) {
return getClassNames(asList(l));
}
static byte[] boolArrayToBytes(boolean[] a) {
byte[] b = new byte[(l(a)+7)/8];
for (int i = 0; i < l(a); i++)
if (a[i])
b[i/8] |= 1 << (i & 7);
return b;
}
static int strL(String s) {
return s == null ? 0 : s.length();
}
static int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
static byte[] byteArrayFromShorts_bigEndian(short[] a) {
return byteArrayFromShorts_bigEndian(a, 0, l(a));
}
static byte[] byteArrayFromShorts_bigEndian(short[] a, int from, int to) {
byte[] b = new byte[(to-from)*2];
for (int i = 0; i < a.length; i++) {
short s = a[from+i];
b[i*2] = (byte) (s >> 8);
b[i*2+1] = (byte) s;
}
return b;
}
static byte[] byteArrayFromLongs_bigEndian(long[] a) {
return byteArrayFromLongs_bigEndian(a, 0, l(a));
}
static byte[] byteArrayFromLongs_bigEndian(long[] a, int from, int to) {
byte[] b = new byte[(to-from)*8];
for (int i = 0; i < a.length; i++) {
long s = a[from+i];
b[i*8] = (byte) (s >> 56);
b[i*8+1] = (byte) (s >> 48);
b[i*8+2] = (byte) (s >> 40);
b[i*8+3] = (byte) (s >> 32);
b[i*8+4] = (byte) (s >> 24);
b[i*8+5] = (byte) (s >> 16);
b[i*8+6] = (byte) (s >> 8);
b[i*8+7] = (byte) s;
}
return b;
}
static List> mapPairB(final Object f, Iterable> l) {
return map(l, new F1, Pair>() { public Pair get(Pair p) { try {
return p == null ? null : pair(p.a, (C) callF(f, p.b));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "p == null ? null : pair(p.a, (C) callF(f, p.b))"; }});
}
static List> mapPairB(final F1 f, Iterable> l) {
return mapPairB((Object) f, l);
}
static List> mapPairB(final IF1 f, Iterable> l) {
return mapPairB((Object) f, l);
}
static List> mapPairB(Iterable> l, IF1 f) {
return mapPairB((Object) f, l);
}
static Pair mapPairB(IF1 f, Pair p) {
return pairMapB(f, p);
}
static Pair mapPairB(Pair p, IF1 f) {
return pairMapB(f, p);
}
static int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
static int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static int cmp(int a, int b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static int cmp(long a, long b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static int cmp(Object a, Object b) {
if (a == null) return b == null ? 0 : -1;
if (b == null) return 1;
return ((Comparable) a).compareTo(b);
}
static Method findMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args);
}
static boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static Map mapToKey(Iterable l, IF1 f) {
return mapToKeys(l, f);
}
static Map mapToKey(IF1 f, Iterable l) {
return mapToKeys(f, l);
}
static String unnullForIteration(String s) {
return s == null ? "" : s;
}
static Collection unnullForIteration(Collection l) {
return l == null ? immutableEmptyList() : l;
}
static List unnullForIteration(List l) { return l == null ? immutableEmptyList() : l; }
static byte[] unnullForIteration(byte[] l) { return l == null ? emptyByteArray() : l; }
static int[] unnullForIteration(int[] l) { return l == null ? emptyIntArray() : l; }
static char[] unnullForIteration(char[] l) { return l == null ? emptyCharArray() : l; }
static double[] unnullForIteration(double[] l) { return l == null ? emptyDoubleArray() : l; }
static short[] unnullForIteration(short[] l) { return l == null ? emptyShortArray() : l; }
static Map unnullForIteration(Map l) {
return l == null ? immutableEmptyMap() : l;
}
static Iterable unnullForIteration(Iterable i) {
return i == null ? immutableEmptyList() : i;
}
static A[] unnullForIteration(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static BitSet unnullForIteration(BitSet b) {
return b == null ? new BitSet() : b;
}
static Pt unnullForIteration(Pt p) {
return p == null ? new Pt() : p;
}
//ifclass Symbol
static Symbol unnullForIteration(Symbol s) {
return s == null ? emptySymbol() : s;
}
//endif
static Pair unnullForIteration(Pair p) {
return p != null ? p : new Pair(null, null);
}
static long unnullForIteration(Long l) { return l == null ? 0L : l; }
static Map> getFieldOrder_cache = weakMap();
static List getFieldOrder(Object o) {
return getFieldOrder(_getClass(o));
}
static List getFieldOrder(Class c) {
if (c == null) return null;
return getOrCreate(getFieldOrder_cache, c,
() -> splitAtSpace(toStringOpt(getOpt(c, "_fieldOrder"))));
}
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 && b != null && c.addAll(Arrays.asList(b));
}
static Map addAll(Map a, Map extends A,? extends B> b) {
if (a != null && b != null) a.putAll(b);
return a;
}
static A addAll(A c, Collection extends Component> components) {
return addComponents(c, components);
}
static A addAll(A c, Component... components) {
return addComponents(c, components);
}
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 isTrue(Boolean b) {
return b != null && b.booleanValue();
}
static boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static boolean isEmpty(File f) {
return f == null || f.length() == 0;
}
static boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static boolean isEmpty(Object[] a) { return a == null || a.length == 0; }
static boolean isEmpty(byte[] a) { return a == null || a.length == 0; }
static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
static boolean isEmpty(AppendableChain c) { return c == null; }
static boolean isEmpty(IntSize l) { return l == null || l.size() == 0; }
static String quickSubstring(String s, int i, int j) {
if (i >= j) return "";
return s.substring(i, j);
}
static PCallPolicy pcallPolicyForThread() {
var policy = pcallPolicyForThread_tl().get();
if (policy != null) return policy;
return defaultPCallPolicy();
}
static boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static String dropPrefixSuffix(String prefix, String s) { return dropPrefixSuffix(prefix, prefix, s); }
static String dropPrefixSuffix(String prefix, String suffix, String s) {
return dropPrefix(prefix, dropSuffix(suffix, s));
}
static short shortFromBytes(byte[] a, int i) {
return (short) (ubyteToInt(a[i]) << 8
| ubyteToInt(a[i+1]));
}
static boolean odd(int i) {
return (i & 1) != 0;
}
static boolean odd(long i) {
return (i & 1) != 0;
}
static boolean odd(BigInteger i) { return odd(toInt(i)); }
static int parseHexChar(char c) {
if (c >= '0' && c <= '9') return charDiff(c, '0');
if (c >= 'a' && c <= 'f') return charDiff(c, 'a')+10;
if (c >= 'A' && c <= 'F') return charDiff(c, 'A')+10;
return -1;
}
static long longFromBytes_bigEndian(byte[] a, int i) {
return twoIntsToLong_bigEndian(
intFromBytes_bigEndian(a, i),
intFromBytes_bigEndian(a, i+4));
}
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 String unquoteSingleOrDoubleQuotes(String s) {
if (s == null) return null;
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length()-1 : s.length();
StringBuilder sb = new StringBuilder(l-1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\"': ch = '\"'; break;
case '\\': ch = '\\'; break;
case 'b': ch = '\b'; break;
case 'f': ch = '\f'; break;
case 'n': ch = '\n'; break;
case 'r': ch = '\r'; break;
case 't': ch = '\t'; break;
case '\'': ch = '\''; break;
// Hex Unicode: u????
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + s.charAt(i + 2) + s.charAt(i + 3)
+ s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar; // added by Stefan
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s; // not quoted - return original
}
static String dropSuffix(String suffix, String s) {
return nempty(suffix) && endsWith(s, suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static boolean addToCollection(Collection c, A a) {
return c != null && c.add(a);
}
static TreeMap caseInsensitiveMap() {
return new TreeMap(caseInsensitiveComparator());
}
static Object safeUnstructure(String s) {
return unstructure(s, true);
}
static Object safeUnstructure(File f) {
return safeUnstructureGZFile(f);
}
static Map synchroHashMap() {
return synchronizedMap(new HashMap());
}
static Object call_withVarargs(Object o, String methodName, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(methodName, args);
if (me != null)
return invokeMethod(me, null, args);
// try varargs
List methods = cache.cache.get(methodName);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
{ if (!(isStaticMethod(m))) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + methodName + "(" + formatArgumentClasses(args) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me != null)
return invokeMethod(me, o, args);
// try varargs
List methods = cache.cache.get(methodName);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + methodName + "(" + formatArgumentClasses(args) + ") not found");
}
} catch (Exception __e) { throw rethrow(__e); } }
static String assertIsIdentifier(String s) {
if (!isIdentifier(s))
throw fail("Not an identifier: " + quote(s));
return s;
}
static String assertIsIdentifier(String msg, String s) {
if (!isIdentifier(s))
throw fail(msg + " - Not an identifier: " + quote(s));
return 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 int[] unnull(int[] l) { return l == null ? emptyIntArray() : l; }
static char[] unnull(char[] l) { return l == null ? emptyCharArray() : l; }
static double[] unnull(double[] l) { return l == null ? emptyDoubleArray() : l; }
static float[] unnull(float[] l) { return l == null ? emptyFloatArray() : 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[]) emptyObjectArray() : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
//ifclass Symbol
static Symbol unnull(Symbol s) {
return s == null ? emptySymbol() : s;
}
//endif
static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static int unnull(Integer i) { return i == null ? 0 : i; }
static long unnull(Long l) { return l == null ? 0L : l; }
static double unnull(Double l) { return l == null ? 0.0 : l; }
static boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static int listL(Collection l) {
return l == null ? 0 : l.size();
}
static Class getOuterClass(Class c) { return getOuterClass(c, null); }
static Class getOuterClass(Class c, Object classFinder) { try {
String s = c.getName();
int i = s.lastIndexOf('$');
String name = substring(s, 0, i);
return classForName(name, classFinder);
} catch (Exception __e) { throw rethrow(__e); } }
static Class getOuterClass(Object o) { return getOuterClass(o, null); }
static Class getOuterClass(Object o, Object classFinder) {
return getOuterClass(_getClass(o), classFinder);
}
static HashMap instanceFieldsMap(Object o) {
return (HashMap) getOpt_getFieldMap(o);
}
static void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
// take care of common case (long to int)
if (type == int.class && value instanceof Long)
{ f.set(o, ((Long) value).intValue()); return; }
if (type == boolean.class && value instanceof String)
{ f.set(o, isTrueOrYes(((String) value))); return; }
if (type == LinkedHashMap.class && value instanceof Map)
{ f.set(o, asLinkedHashMap((Map) value)); return; }
try {
if (f.getType() == Concept.Ref.class)
{ f.set(o, ((Concept) o).new Ref((Concept) value)); return; }
if (o instanceof Concept.Ref)
{ f.set(o, ((Concept.Ref) o).get()); return; }
} catch (Throwable _e) {}
throw e;
}
}
static Field setOpt_findField(Class c, String field) {
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map.get(field);
}
static void setOpt(Object o, String field, Object value) { try {
if (o == null) return;
Class c = o.getClass();
HashMap map;
if (getOpt_cache == null)
map = getOpt_makeCache(c); // in class init
else synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
// It's probably a subclass of Map. Use raw method. TODO: huh?
setOpt_raw(o, field, value);
return;
}
Field f = map.get(field);
if (f != null)
{ smartSet(f, o, value); return; } // possible improvement: skip setAccessible
if (o instanceof DynamicObject)
{ setDyn(((DynamicObject) o), field, value); return; }
if (o instanceof IMeta)
setDyn(((IMeta) o), field, value);
} catch (Exception __e) { throw rethrow(__e); } }
static void setOpt(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = setOpt_findStaticField(c, field); // TODO: optimize
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
makeAccessible(f);
return f;
}
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static String exceptionToStringShort(Throwable e) {
try {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
} catch (Throwable _e) { printStackTrace(_e);
return "Error in exceptionToStringShort";
}
}
static void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
static Map thisDollarOneFields_cache = newDangerousWeakHashMap();
static Field[] thisDollarOneFields(Class c) {
synchronized(thisDollarOneFields_cache) {
Field[] l = thisDollarOneFields_cache.get(c);
if (l == null)
thisDollarOneFields_cache.put(c, l = thisDollarOneFields_uncached(c));
return l;
}
}
static Field[] thisDollarOneFields_uncached(Class c) {
List fields = new ArrayList();
do {
for (Field f : c.getDeclaredFields())
if (f.getName().startsWith("this$"))
fields.add(makeAccessible(f));
c = c.getSuperclass();
} while (c != null);
return toArray(new Field[l(fields)], fields);
}
static Method fastIntern_method;
static String fastIntern(String s) { try {
if (s == null) return null;
if (fastIntern_method == null) {
fastIntern_method = findMethodNamed(javax(), "internPerProgram");
if (fastIntern_method == null) upgradeJavaXAndRestart();
}
return (String) fastIntern_method.invoke(null, s);
} catch (Exception __e) { throw rethrow(__e); } }
static Map> callOpt_noArgs_cache = newDangerousWeakHashMap();
static Object callOpt_noArgs(Object o, String method) { try {
if (o == null) return null;
if (o instanceof Class)
return callOpt(o, method); // not optimized
Class c = o.getClass();
HashMap map;
synchronized(callOpt_noArgs_cache) {
map = callOpt_noArgs_cache.get(c);
if (map == null)
map = callOpt_noArgs_makeCache(c);
}
Method m = map.get(method);
return m != null ? m.invoke(o) : null;
} catch (Exception __e) { throw rethrow(__e); } }
// used internally - we are in synchronized block
static HashMap callOpt_noArgs_makeCache(Class c) {
HashMap map = new HashMap();
Class _c = c;
do {
for (Method m : c.getDeclaredMethods())
if (m.getParameterTypes().length == 0
&& !reflection_isForbiddenMethod(m)) {
makeAccessible(m);
String name = m.getName();
if (!map.containsKey(name))
map.put(name, m);
}
_c = _c.getSuperclass();
} while (_c != null);
callOpt_noArgs_cache.put(c, map);
return map;
}
static LinkedHashMap syncMapPut2_createLinkedHashMap(LinkedHashMap map, A key, B value) {
if (key != null)
if (value != null) {
if (map == null) map = new LinkedHashMap();
synchronized(collectionMutex(map)) { map.put(key, value); }
} else if (map != null) synchronized(collectionMutex(map)) { map.remove(key); }
return map;
}
static TreeSet caseInsensitiveSet() {
return caseInsensitiveSet_treeSet();
}
static TreeSet caseInsensitiveSet(Collection c) {
return caseInsensitiveSet_treeSet(c);
}
// TODO: extended multi-line strings
static int javaTok_n, javaTok_elements;
static boolean javaTok_opt = false;
static List