Warning : session_start(): open(/var/lib/php/sessions/sess_bcb79akk00c6ok58phlf0q0m5b, 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
1400555
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;
import java.awt.geom.*;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.Const;
import org.apache.bcel.generic.*;
import java.lang.reflect.Type;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import static x30_pkg.x30_util.DynamicObject;
import java.util.jar.*;
import java.text.*;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;
import java.nio.charset.Charset;
import java.util.TimeZone;
import java.nio.file.Path;
public class main {
static public class test_leftArrowScript_ClassA {
}
static public class test_leftArrowScript_ClassB extends test_leftArrowScript_ClassA {
}
static public class test_leftArrowScript_ClassC extends test_leftArrowScript_ClassB {
}
static public class test_leftArrowScript_StaticField {
static public String theField;
}
static public class test_leftArrowScript_StaticFieldSubClass extends test_leftArrowScript_StaticField {
}
public interface test_leftArrowScript_StaticFieldInInterface {
static public String daField = "yo";
}
static public class test_leftArrowScript_StaticFieldInterfaceImplementor implements test_leftArrowScript_StaticFieldInInterface {
}
static public class test_leftArrowScript_InheritanceDispatchTest {
static public String f(test_leftArrowScript_ClassA a) {
return "a";
}
static public String f(test_leftArrowScript_ClassB a) {
return "b";
}
}
static public class test_leftArrowScript_Tester {
public Object value = "123";
static public Object myStaticField = "ok";
}
static public class test_leftArrowScript_Sub1 {
static public class X {
static public int value = 1;
}
}
static public class test_leftArrowScript_Sub2 {
static public class X {
static public int value = 2;
}
}
public interface test_leftArrowScript_DefaultMethodInterface {
default public String x() {
return "y";
}
}
static public class test_leftArrowScript_DefaultMethodTest implements test_leftArrowScript_DefaultMethodInterface {
}
static public void test_leftArrowScript() {
test_leftArrowScript_pinging();
final class _C_2 {
public String countLoop(int n) {
return " i <- 0; while lessThan i " + n + " { i <- plus i 1 }; i ";
}
}
final _C_2 __3 = new _C_2();
String ifThenElseScript = "\r\n if lessThan a b { joinWithSpace \"It's\" \"less\" }\r\n else if greaterThan a b { joinWithSpace \"It's\" \"greater\" }\r\n else { joinWithSpace \"They're\" \"equal\" }\r\n ";
testFunctionValues(script -> leftArrowVerbose((String) script), " 5 ", 5, " -5 ", -5, "\r\n def double x {\r\n Math multiplyExact x 2\r\n }\r\n \r\n double 10\r\n ", 20, " new Pair \"hello\" \"world\" ", pair("hello", "world"), " str 1.5e2 ", "150.0", " 1.5e2f ", 150f, " 1.5e2F ", 150f, " 0L ", 0L, " 0x80 ", 0x80, " 0B101 ", 0B101, " '\\t' ", '\t', " Color black ", Color.black, " tester <- new test_leftArrowScript_Tester; tester value ", "123", __3.countLoop(5), 5, " if lessThan 0 1 { \"ok\" } ", "ok", " if lessThan 1 0 { \"ok\" } ", null, " l <- ll 2 3\r\n sum <- 0\r\n for number in l { sum <- plus sum number }\r\n sum\r\n ", 5, " for i in ll 2 3 { plus i 1 }\r\n ", ll(3, 4), " joinWithSpace (for i in ll 2 3 { i }) ", "2 3", " for i to 2 { i }\r\n ", ll(0, 1), " for b in litbytearray (toByte 5) (toByte 7) { b } ", ll((byte) 5, (byte) 7), " for b in litdoublearray 5.0 7.0 { b } ", ll(5.0, 7.0), " for c in chars \"AB\" { c } ", ll('A', 'B'), " for c: char in chars \"AB\" { c } ", ll('A', 'B'), "\r\n img <- newImage 10 10\r\n r <- randomRect img 10 10\r\n ", rect(0, 0, 10, 10), "\r\n a <- 1\r\n b <- a\r\n a\r\n ", 1, "\r\n a <- 1\r\n a <- null\r\n a\r\n ", null, "\r\n return 17\r\n ", 17, "\r\n return 13\r\n return 22\r\n ", 13, "\r\n ret 13\r\n ret 22\r\n ", 13, "\r\n if true { return \"so true\" }\r\n return \"oops\"\r\n ", "so true", "\r\n if false { return \"not true\" }\r\n return \"but this\"\r\n ", "but this", " a <- 1; b <- 2; " + ifThenElseScript, "It's less", " a <- 6; b <- 2; " + ifThenElseScript, "It's greater", " a <- 5.0; b <- 5.0; " + ifThenElseScript, "They're equal", " if true then \"ok\" else \"not ok\" ", "ok", " if false then \"ok\" else \"not ok\" ", "not ok", " plus (plus 1 2) 4 ", 7, " (plus 5 6) toString ", "11", " (plus 1\r\n (plus 2 3)) ", 6, " str (Color black) ", str(Color.black), " (for y in ll 1 {\r\n new Pair 1 2\r\n for x in null {}\r\n }); 0 ", 0, " param x; x ", null, " param x : int; x ", null, " return x <- 1 ", 1, " for pair a b in ll (pair 1 2) (pair 3 4) {\r\n plus a b\r\n } ", ll(3, 7), " for a, b in litorderedmap 1 2 3 4 {\r\n plus a b\r\n } ", ll(3, 7), " for index i, a in ll \"a\" \"b\" {\r\n concatStrings i a\r\n } ", ll("0a", "1b"), " longPlus 1 2 ", 3L, " new Ratio 1 ", new Ratio(1), " def f1 { 1 }\r\n def f2 { plus (f1) 2 }\r\n f2 ", 3, " for x in iota 2 { return x } ", 1, " for x in iota 2 {\r\n if eq x 1 { continue }\r\n return \"ok\"\r\n } ", "ok", " Pair (neg 1) (neg 2) ", pair(-1, -2), " neg <- neg 1; neg ", -1, " x <- 0\r\n repeat plus 1 2 { x <- plus x 1 }\r\n x ", 3, " x <- 0\r\n def incIt { outer x <- plus x 1 }\r\n incIt\r\n x ", 1, " if true { return } ", null, " repF 2 (IF0 -> { return 1; null }) ", ll(1, 1), " list <- new ArrayList\r\n {\r\n temp tempAdd list 5\r\n assertContains list 5\r\n }\r\n list\r\n ", ll(), " list <- new ArrayList\r\n pcallF (Runnable -> {\r\n temp tempAdd list 5\r\n fail\r\n })\r\n list\r\n ", ll(), " list <- new ArrayList\r\n {\r\n temp x <- tempAdd list 5\r\n assertInstanceOf x AutoCloseable\r\n assertContains list 5\r\n }\r\n list\r\n ", ll(), " main ", mc(), " java.util.Arrays sort (newFloatArray 1) ", null, " new java.util.ArrayList ", ll(), " \"\" length ", 0, " new List ", ll(), " new L ", ll(), " new Map ", new HashMap(), " c <- ArrayList; new c ", ll(), " new Var, getClass ", Var.class, shortName(test_leftArrowScript_InheritanceDispatchTest.class) + " f (new " + shortName(test_leftArrowScript_ClassC.class) + ")", "b", "\r\n sleepSeconds 0\r\n sleepSeconds 0\r\n ", null, " a : S <- \"s\"; a ", "s", "\r\n a <- 0\r\n try {\r\n try { a <- plus a 1 } finally { a <- plus a 2 }\r\n try { fail } finally { a <- plus a 3 }\r\n } catch e {}\r\n a\r\n ", 6, "\r\n list {\r\n try { fail } catch {}\r\n try { fail } catch { \"oops\" }\r\n try { \"a\" } catch {}\r\n }\r\n ", ll(null, "oops", "a"), "\r\n def f x: int {\r\n plus x 1\r\n }\r\n f 5\r\n ", 6, "\r\n def f (x: int) {\r\n plus x 1\r\n }\r\n f 5\r\n ", 6, "\r\n param x : L>\r\n ", null, " x <- 5; ll +x ", ll("x", 5), "splitAtSpace [[a b", ll("a", "b"), "splitAtSpace [=[c d", ll("c", "d"), " list {\r\n plus 1 2\r\n minus 8 4\r\n } ", ll(3, 4), " list { plus 1 2; minus 8 4 } ", ll(3, 4), " for x in ll\r\n 1 { x } ", ll(1), " data <- new Var\r\n will return data get\r\n data set 1 ", 1, " def myFactorial n {\r\n if n lessThan 2\r\n { 1 }\r\n else { myFactorial (n minus 1), mul n }\r\n }\r\n myFactorial 5\r\n ", 120, "\r\n iterator <- new TestCloseableIterableIterator\r\n closed <- new Flag\r\n iterator onClosing closed\r\n for i in iterator {}\r\n closed isUp\r\n ", true, "\r\n iterator <- new TestCloseableIterableIterator\r\n closed <- new Flag\r\n iterator onClosing closed\r\n try {\r\n for i in iterator { fail }\r\n } catch e {}\r\n closed isUp\r\n ", true, " new Timestamp 1000, unixDate ", 1000L, " a <- null; a intValue? ", null, " a <- 5L; a intValue? ", 5, " 1234567812345678 ", 1234567812345678L, " d: Duration <- daysToDuration 1 ", daysToDuration(1), " fileName < first < toTypedArray File < ll < newFile \"hello\" ", "hello", "\r\n o <- new O\r\n assertFalse < Thread holdsLock o\r\n synchronized o {\r\n assertTrue < Thread holdsLock o\r\n }\r\n assertFalse < Thread holdsLock o\r\n null\r\n ", null, " a <- \"1\"; b <- \"2\"; new Pair, +a, +b ", pair("1", "2"), jreplace(" new DefaultMethodTest, x ", "DefaultMethodTest", shortName(test_leftArrowScript_DefaultMethodTest.class)), "y");
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
enableScaffolding(parser);
parser.allowTheWorld();
FlexibleVarContext ctx = new FlexibleVarContext();
assertSame(ctx, parser.parse("_context").get(ctx));
test_leftArrowScriptParseErrors();
test_leftArrowScript_lambdas();
test_leftArrowScript_binaryOperators();
test_leftArrowScriptCompileErrors();
parser = new GazelleV_LeftArrowScriptParser();
parser.allowTheWorld(test_leftArrowScript_Tester.class, mc());
assertEqualsVerbose("ok", parser.parse("myStaticField").get());
assertEqualsVerbose("ko", parser.parse("reversed myStaticField").get());
assertEqualsVerbose(2, parser.parse("myStaticField length").get());
test_leftArrowScript_classDefs();
test_leftArrowScript_forIterator();
var exception = leftArrowVerbose("\r\n try { throw new RuntimeException } catch e { e }\r\n ");
assertEqualsVerbose(exception.getClass(), RuntimeException.class);
assertFailVerbose(() -> leftArrowVerbose(" \"\" lengthX "));
assertFailVerbose(() -> leftArrowParse(" def x { y <- 1 } y "));
test_leftArrowScript_comma();
test_leftArrowScript_antiComma();
parser = new GazelleV_LeftArrowScriptParser();
enableScaffolding(parser);
parser.allowTheWorld(test_leftArrowScript_Sub1.class, test_leftArrowScript_Sub2.class);
assertEqualsVerbose(1, parser.parse("X value").get());
parser = new GazelleV_LeftArrowScriptParser();
enableScaffolding(parser);
parser.allowTheWorld(test_leftArrowScript_Sub2.class, test_leftArrowScript_Sub1.class);
assertEqualsVerbose(2, parser.parse("X value").get());
test_leftArrowScript_returnValueNotNeededOptimization();
parser = new GazelleV_LeftArrowScriptParser();
parser.allowTheWorld();
parser.addClassAlias("Paar", "Pair");
assertEqualsVerbose(pair(1, 2), parser.parse("new Paar 1 2").get());
var script = leftArrowParseVerbose("param x : int");
assertEqualsVerbose(1, l(script.params));
assertEqualsVerbose("x", firstKey(script.params));
assertEqualsVerbose(int.class, firstValue(script.params).javaClass());
assertFailVerbose(() -> leftArrowParseVerbose(" x <- 5; ll + x "));
test_leftArrowScript_magicSwitch();
test_leftArrowScript_tilde();
test_leftArrowScript_then();
assertInstanceOf(IF0.class, leftArrowVerbose(" abcd <- IF0 {}; abcd "));
Object o = leftArrow("def bla { null } ");
assertEqualsVerbose("bla", ((GazelleV_LeftArrowScript.FunctionDef) o).name);
o = leftArrow("a <- def bla { null }; a");
assertEqualsVerbose("bla", ((GazelleV_LeftArrowScript.FunctionDef) o).name);
test_leftArrowScript_pcall();
test_leftArrowScript_ifdef();
leftArrowVerbose(replace(" StaticField theField <- \"hello\"\r\n ", "StaticField", className(test_leftArrowScript_StaticField.class)));
assertEqualsVerbose("hello", test_leftArrowScript_StaticField.theField);
assertEqualsVerbose("hello", leftArrowVerbose(replace(" StaticFieldSubClass theField ", "StaticFieldSubClass", className(test_leftArrowScript_StaticFieldSubClass.class))));
assertEqualsVerbose("yo", leftArrowVerbose(replace(" StaticFieldInterfaceImplementor daField ", "StaticFieldInterfaceImplementor", className(test_leftArrowScript_StaticFieldInterfaceImplementor.class))));
test_leftArrowScript_scriptError();
test_leftArrowScript_objectScope();
test_leftArrowScript_doWhile();
assertSame(intern("abc"), leftArrowVerbose("\"abc\""));
print("All left-arrow script tests OK!");
}
static public Method findMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args);
}
static public 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 public String concat(Object... l) {
return concatStrings(l);
}
static public String concat(Iterable l) {
return concatStrings(l);
}
static public Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
static public RuntimeException fail() {
throw new RuntimeException("fail");
}
static public RuntimeException fail(Throwable e) {
throw asRuntimeException(e);
}
static public RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static public RuntimeException fail(Object... objects) {
throw new Fail(objects);
}
static public RuntimeException fail(String msg) {
throw new RuntimeException(msg == null ? "" : msg);
}
static public RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
static public char[] chars(String s) {
return asChars(s);
}
static public Class _getClass2(Object o) {
return o == null ? null : o.getClass();
}
static public Duration daysToDuration(double days) {
return msToDuration(daysToMS(days));
}
static public A getVar(IF0 v) {
return v == null ? null : v.get();
}
static public A getVar(Optional v) {
return v == null ? null : v.orElse(null);
}
static public double[] litdoublearray(double... l) {
return cloneDoubleArray(l);
}
static public BigInteger mul(BigInteger a, BigInteger b) {
return a.multiply(b);
}
static public BigInteger mul(BigInteger a, long b) {
return a.multiply(bigint(b));
}
static public int mul(int a, int b) {
return a * b;
}
static public long mul(long a, long b) {
return a * b;
}
static public double mul(double a, double b) {
return a * b;
}
static public void nop() {
}
static public byte toByte(Object o) {
if (o == null)
return (byte) 0;
if (o instanceof Number)
return ((Number) o).byteValue();
if (o instanceof String)
return toByte(parseInt((String) o));
throw fail("not convertible to byte: " + getClassName(o));
}
static public byte toByte(int i) {
return (byte) i;
}
static public byte[] litbytearray(byte... l) {
return cloneByteArray(l);
}
static public List splitAtSpace(String s) {
return empty(s) ? emptyList() : asList(s.split("\\s+"));
}
static public Pt neg(Pt p) {
return p == null ? null : new Pt(-p.x, -p.y);
}
static public int neg(int i) {
return -i;
}
static public double neg(double i) {
return -i;
}
static public void sleepSeconds(double s) {
if (s > 0)
sleep(round(s * 1000));
}
static public float[] newFloatArray(int n) {
return new float[n];
}
static public long nanoTime() {
return System.nanoTime();
}
static public List reversed(Iterable l) {
return reversedList(l);
}
static public List reversed(A[] l) {
return reversedList(asList(l));
}
static public String reversed(String s) {
return reversedString(s);
}
static public AutoCloseable tempAdd(Collection l, A a) {
if (l == null || l.contains(a))
return null;
l.add(a);
return new tempAdd_undo(l, a);
}
static public class tempAdd_undo implements AutoCloseable, IFieldsToList {
public Collection l;
public A a;
public tempAdd_undo() {
}
public tempAdd_undo(Collection l, A a) {
this.a = a;
this.l = l;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + l + ", " + a + ")";
}
public Object[] _fieldsToList() {
return new Object[] { l, a };
}
public void close() {
try {
l.remove(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
static public AutoCloseable tempAdd(Container a, Component b) {
if (a == null || b == null)
return null;
{
return swing(() -> {
if (b.getParent() == a)
return null;
a.add(b);
return () -> {
swing(() -> {
if (b.getParent() == a)
removeFromParent(b);
});
};
});
}
}
static public String concatStrings(Object... l) {
return join("", l);
}
static public String concatStrings(Iterable l) {
return join("", l);
}
static public BigInteger plus(BigInteger a, BigInteger b) {
return a.add(b);
}
static public BigInteger plus(BigInteger a, long b) {
return a.add(bigint(b));
}
static public long plus(long a, long b) {
return a + b;
}
static public int plus(int a, int b) {
return a + b;
}
static public float plus(float a, float b) {
return a + b;
}
static public double plus(double a, double b) {
return a + b;
}
static public List minus(Collection a, Object... b) {
Set set = asSet(b);
List l = new ArrayList();
for (Object s : unnull(a)) if (!set.contains(s))
l.add(s);
return l;
}
static public BigInteger minus(BigInteger a, BigInteger b) {
return a.subtract(b);
}
static public Complex minus(Complex c) {
return c == null ? null : complex(-c.re(), -c.im());
}
static public int minus(int a, int b) {
return a - b;
}
static public int minus(int a) {
return -a;
}
static public double minus(double a, double b) {
return a - b;
}
static public double minus(double a) {
return -a;
}
static public long minus(long a, long b) {
return a - b;
}
static public long minus(long a) {
return -a;
}
static public boolean lessThan(int a, int b) {
return a < b;
}
static public boolean lessThan(double a, double b) {
return a < b;
}
static public boolean lessThan(Object a, Object b) {
return cmp(a, b) < 0;
}
static public boolean greaterThan(Object a, Object b) {
return cmp(a, b) > 0;
}
static public boolean greaterThan(int a, int b) {
return a > b;
}
static public boolean greaterThan(double a, double b) {
return a > b;
}
static public BufferedImage newImage(int w, int h) {
return whiteImage(w, h);
}
static public BufferedImage newImage(int w, Color color) {
return newImage(w, w, color);
}
static public BufferedImage newImage(int w, int h, Color color) {
return bufferedImage(w, h, color);
}
static public BufferedImage newImage(int size) {
return whiteImage(size);
}
static public BufferedImage newImage(Pt size) {
return whiteImage(size.x, size.y);
}
static public BufferedImage newImage(WidthAndHeight size) {
return whiteImage(size.w(), size.h());
}
static public BufferedImage newImage(Dimension size) {
return whiteImage(size.width, size.height);
}
static public Rect randomRect(Rect outer) {
var w = random_incl(outer.w);
var h = random_incl(outer.h);
return randomRect(w, h, outer);
}
static public Rect randomRect(int w, int h, Rect outer) {
return translateRect(outer.x, outer.y, randomRect(outer.w, outer.h, 0, w, h));
}
static public Rect randomRect(Rect outer, int w, int h) {
return randomRect(w, h, outer);
}
static public Rect randomRect(int w, int h, int rw, int rh) {
return randomRect(w, h, 0, rw, rh);
}
static public Rect randomRect(int w, int h, int border, int rw, int rh) {
if (rw > w - border * 2 || rh > h - border * 2)
return null;
int ww = random(border, w - border - rw);
int hh = random(border, h - border - rh);
return new Rect(ww, hh, rw, rh);
}
static public Rect randomRect(int w, int h) {
int rw = random(w);
int rh = random(h);
return randomRect(w, h, 0, rw, rh);
}
static public Rect randomRect() {
return randomRect(currentImage().getWidth(), currentImage().getHeight());
}
static public Rect randomRect(BufferedImage img, int rw, int rh) {
return randomRect(img.getWidth(), img.getHeight(), 0, rw, rh);
}
static public long longPlus(long a, long b) {
return a + b;
}
static public int intSum(Collection c, String field) {
int sum = 0;
for (Object o : unnull(c)) sum += toInt(getOpt(o, field));
return sum;
}
static public int intSum(Iterable l) {
int sum = 0;
for (Integer i : unnull(l)) if (i != null)
sum += i;
return sum;
}
static public int intSum(int... l) {
int sum = 0;
for (int i : unnull(l)) sum += i;
return sum;
}
static public List repF(int n, Object f, Object... args) {
List l = emptyList(n);
for (int i = 0; i < n; i++) l.add(callF(f, args));
return l;
}
static public List repF(Object f, int n) {
return repF(n, f);
}
static public List repF(int n, IF0 f) {
List l = emptyList(n);
for (int i = 0; i < n; i++) l.add(f.get());
return l;
}
static public List repF(IF0 f, int n) {
return repF(n, f);
}
static public IterableIterator iota(final int n) {
return new IterableIterator() {
public int i = 0;
public boolean hasNext() {
return i < n;
}
public Integer next() {
return ++i;
}
};
}
static public > C assertContains(C c, A y) {
return assertContains(null, c, y);
}
static public > C assertContains(String msg, C c, A y) {
if (!contains(c, y))
throw fail((msg != null ? msg + ": " : "") + y + " not contained in " + c);
return c;
}
static public String assertContains(String a, String b) {
if (!contains(a, b))
throw fail(quote(b) + " not contained in " + quote(a));
return a;
}
static public void assertNotEquals(String msg, Object a, Object b) {
if (eq(a, b))
throw fail(msg);
}
static public void assertNotEquals(Object a, Object b) {
if (eq(a, b))
throw fail(str(a));
}
static public File userDir() {
return new File(userHome());
}
static public File userDir(String path) {
return new File(userHome(), path);
}
static public String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static public String f2s(String s) {
return f2s(newFile(s));
}
static public String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
static public File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static public File newFile(String name) {
return name == null ? null : new File(name);
}
static public File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static public void test_leftArrowScript_pinging() {
final class _C_1 {
public String countLoop(int n) {
return " i <- 0; while lessThan i " + n + " { i <- plus i 1 }; i ";
}
}
final _C_1 __2 = new _C_1();
var script1 = leftArrowParse(__2.countLoop(5));
var script2 = leftArrowParse(__2.countLoop(6));
long pingCount1 = countPingCalls(() -> script1.get());
long pingCount2 = countPingCalls(() -> script2.get());
printVars("pingCount1", pingCount1, "pingCount2", pingCount2);
assertTrue(pingCount2 > pingCount1);
}
static public void testFunctionValues(IF1 function, Object... params) {
for (int i = 0; i + 1 < l(params); i += 2) {
Object in = params[i], expected = params[i + 1];
testFunctionValue(function, in, expected);
}
}
static public Object leftArrowVerbose(LASClassLoader lasClassLoader, String script) {
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
parser.lasClassLoader(lasClassLoader);
return leftArrowVerbose(parser, script);
}
static public Object leftArrowVerbose(String script) {
return leftArrowVerbose(new GazelleV_LeftArrowScriptParser(), script);
}
static public Object leftArrowVerbose(GazelleV_LeftArrowScriptParser parser, String script) {
if (parser.lasClassLoader() != null)
parser.lasClassLoader().rememberClassBytes(true);
enableScaffolding(parser);
parser.allowTheWorld();
var parsedScript = parser.parse(script);
parser.printFunctionDefs(parsedScript);
print(parsedScript);
print("leftArrowVerbose:\n" + GazelleV_LeftArrowScript.indentedScriptStruct(parsedScript));
FlexibleVarContext ctx = new FlexibleVarContext();
var result = parsedScript.get(ctx);
ctx.printMe();
return result;
}
static public Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
static public List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
static public Rect rect(int x, int y, int w, int h) {
return new Rect(x, y, w, h);
}
static public Rect rect(Pt p, int w, int h) {
return new Rect(p.x, p.y, w, h);
}
static public Rect rect(int w, int h) {
return new Rect(0, 0, w, h);
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return c == null ? "null" : new String(c);
}
static public String str(char[] c, int offset, int count) {
return new String(c, offset, count);
}
static public Class mc() {
return main.class;
}
static public String shortName(Object o) {
return shortClassName(o);
}
static public String jreplace(String s, String in, String out) {
return jreplace(s, in, out, null);
}
static public String jreplace(String s, String in, String out, Object condition) {
List tok = javaTok(s);
return jreplace(tok, in, out, condition) ? join(tok) : s;
}
static public boolean jreplace(List tok, String in, String out) {
return jreplace(tok, in, out, false, true, null);
}
static public boolean jreplace(List tok, String in, String out, Object condition) {
return jreplace(tok, in, out, false, true, condition);
}
static public boolean jreplace(List tok, String in, ITokCondition condition, String out) {
return jreplace(tok, in, out, (Object) condition);
}
static public boolean jreplace(List tok, String in, String out, IF2, Integer, Boolean> condition) {
return jreplace(tok, in, out, (Object) condition);
}
static public boolean jreplace(List tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) {
String[] toks = javaTokForJFind_array(in);
int lTokin = toks.length * 2 + 1;
boolean anyChange = false;
int i = -1;
for (int n = 0; n < 10000; n++) {
i = findCodeTokens(tok, i + 1, ignoreCase, toks, condition);
if (i < 0)
return anyChange;
List subList = tok.subList(i - 1, i + lTokin - 1);
String expansion = jreplaceExpandRefs(out, subList);
int end = i + lTokin - 2;
clearAllTokens(tok, i, end);
tok.set(i, expansion);
if (reTok)
reTok(tok, i, end);
i = end;
anyChange = true;
}
throw fail("woot? 10000! " + quote(in) + " => " + quote(out));
}
static public boolean jreplace_debug = false;
static public A enableScaffolding(A o) {
return enableScaffolding(o, true);
}
static public A enableScaffolding(A o, boolean b) {
if (o instanceof IMeta)
((IMeta) o).metaPut("scaffolding", trueOrNull(b));
return o;
}
static public void assertSame(Object a, Object b) {
assertSame("", a, b);
}
static public void assertSame(String msg, Object a, Object b) {
if (a != b)
throw fail(joinNemptiesWithColon(msg, a + " != " + b + " (" + identityHash(a) + "/" + identityHash(b) + ")"));
}
static public void assertSame(IF0 msg, Object a, Object b) {
if (a != b)
throw fail(joinNemptiesWithColon(msg.get(), a + " != " + b + " (" + identityHash(a) + "/" + identityHash(b) + ")"));
}
static public void test_leftArrowScriptParseErrors() {
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
var e = assertFail(() -> parser.parse("unknownIdentifier"));
var inner = innerExceptionOfType(GazelleV_LeftArrowScriptParser.UnknownObject.class, e);
assertEqualsVerbose("unknownIdentifier", inner.name);
assertFail(() -> parser.parse("a <-"));
assertFail(() -> parser.parse("}"));
}
static public class test_leftArrowScript_lambdas_MyClass implements IFieldsToList {
public int x;
public test_leftArrowScript_lambdas_MyClass() {
}
public test_leftArrowScript_lambdas_MyClass(int x) {
this.x = x;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + x + ")";
}
public boolean equals(Object o) {
if (!(o instanceof test_leftArrowScript_lambdas_MyClass))
return false;
test_leftArrowScript_lambdas_MyClass __3 = (test_leftArrowScript_lambdas_MyClass) o;
return x == __3.x;
}
public int hashCode() {
int h = -932327654;
h = boostHashCombine(h, _hashCode(x));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { x };
}
}
static public void test_leftArrowScript_lambdas() {
var test = new TestFunctionValues(__1 -> leftArrowVerbose(__1));
test.io("map (IF1 l) (ll \"hey ho\" \"world\")", ll(6, 5)).runAndClear();
test.io("IF0 mul 2 5L, get", 10L).runAndClear();
new TestFunctionValues(__2 -> leftArrowVerbose(__2)).io("map (IF1 plus 5) (ll 2 12)", ll(7, 17)).run();
class X {
public int i = 1;
public int next() {
return i++;
}
}
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
parser.allowTheWorld(new X(), mc());
assertEqualsVerbose(ll(1, 2, 3), parser.parse("repF 3 (IF0 next)").get());
test.io("\r\n def twice x { joinWithSpace x x }\r\n map (IF1 twice) (ll \"yes\" \"no\")\r\n ", ll("yes yes", "no no"));
test.io("\r\n def subFrom100 a b c { minus 100 (intSum a b c) }\r\n map (IF1 subFrom100 10 5) (ll 2 22)\r\n ", ll(83, 63));
test.runAndClear();
test.io("map (IF1 a -> new Pair a (neg a)) (ll 1 2)", ll(pair(1, -1), pair(2, -2))).runAndClear();
test.io("map (IF1 " + shortClassName(test_leftArrowScript_lambdas_MyClass.class) + ") (ll 1 2)", ll(new test_leftArrowScript_lambdas_MyClass(1), new test_leftArrowScript_lambdas_MyClass(2))).runAndClear();
test.io("map (IF1 a -> { x <- plus a a; plus x x }) (ll 3 5)", ll(3 * 4, 5 * 4)).runAndClear();
test.io("repF 2 < IF0 { 5 }", ll(5, 5)).runAndClear();
test.io(" map (IF1 _ length) < splitAtSpace \"hello you\" ", ll(5, 3)).io(" map (IF1 _ charAt 0) < splitAtSpace \"hello you\" ", ll('h', 'y')).runAndClear();
assertInstanceOf(leftArrowVerbose("\r\n lambda <- (IF1 a -> plus a a)\r\n assertEquals (lambda hashCode) (lambda hashCode)\r\n lambda hashCode\r\n "), Integer.class);
leftArrowVerbose("\r\n lambda1 <- (IF1 a -> plus a a)\r\n lambda2 <- IF1 neg\r\n assertEquals lambda1 lambda1\r\n assertNotEquals lambda1 lambda2\r\n assertEquals lambda2 lambda2\r\n assertNotEquals lambda2 lambda1\r\n ");
test.io("\r\n action <- IF0 -> \"ok\"\r\n action get\r\n ", "ok").runAndClear();
test.io("\r\n (IF0 -> \"ok\") get\r\n ", "ok").runAndClear();
test.io("(IF1 a: S -> new Pair a a) get \"x\"", pair("x")).runAndClear();
test.io("\r\n (Comparator a b -> cmp a b) compare 1 2\r\n ", -1).runAndClear();
}
static public void test_leftArrowScript_binaryOperators() {
var test = new TestFunctionValues(__1 -> leftArrowVerbose(__1));
test.io("&& true false", false).io("&& true true", true).io("&& false true", false).io("&& false false", false).io("&& false (fail)", false).runAndClear();
}
static public void test_leftArrowScriptCompileErrors() {
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
parser.allowTheWorld();
String src = "Pair a";
assertFail(src, () -> printIndentedStruct(parser.parse(src)));
}
static public A assertEqualsVerbose(Object x, A y) {
assertEqualsVerbose((String) null, x, y);
return y;
}
static public 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) + ": " + (x));
return y;
}
static public void assertEqualsVerbose(Scorer scorer, Object x, Object y) {
assertEqualsVerbose(scorer, "", x, y);
}
static public 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 public void test_leftArrowScript_classDefs() {
LASMultiClassLoader cl = new LASMultiClassLoader(mc());
try {
test_leftArrowScript_classDefs(cl);
} finally {
_close(cl);
}
}
static public class test_leftArrowScript_classDefs_Base {
public String hey() {
return "ho";
}
}
static public void test_leftArrowScript_classDefs(LASMultiClassLoader cl) {
var test = new TestFunctionValues(__3 -> leftArrowVerbose(__3));
String classPrefix = "scriptClasses.";
final class _C_1 {
public Object runScript(String code) {
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
enableScaffolding(parser);
parser.classDefPrefix(classPrefix);
parser.lasClassLoader(cl);
return leftArrowVerbose(parser, code);
}
}
final _C_1 __2 = new _C_1();
String classSrc = "\r\n class MyClass {\r\n a: String\r\n b: String\r\n }\r\n ", src = classSrc;
Class c = (Class) (__2.runScript(src));
assertStartsWith(print(c.getName()), classPrefix + "MyClass" + "_");
assertSame(c, __2.runScript(src));
assertEqualsVerbose("Number of fields", 3, l(getDeclaredFields_cached(c)));
assertEqualsVerbose("Type of a", String.class, getField(c, "a").getType());
assertEqualsVerbose("Type of b", String.class, getField(c, "b").getType());
Class c2 = (Class) (__2.runScript("\r\n class MyClass {\r\n a: String\r\n c: String\r\n }\r\n "));
print(className(c2));
assertNotSame(c, c2);
String classSrc2 = "\r\n class MyClass {\r\n def bla { \"x\" }\r\n }\r\n ";
c = (Class) __2.runScript(classSrc2);
assertSame(c, __2.runScript(classSrc2));
c2 = (Class) __2.runScript("\r\n class MyClass {\r\n def bla { \"y\" }\r\n }\r\n ");
assertNotSame(c, c2);
src = classSrc + "\r\n x <- new MyClass\r\n y <- new MyClass\r\n x a <- \"yo\"\r\n y a <- \"oy\"\r\n x a\r\n ";
assertEqualsVerbose("yo", __2.runScript(src));
src = classSrc + "\r\n def bla {\r\n x <- new MyClass\r\n x a <- \"yo\"\r\n x a\r\n }\r\n bla\r\n ";
assertEqualsVerbose("yo", __2.runScript(src));
src = "\r\n class MyClass2 {\r\n def method1 { \"I'm here\" }\r\n def method2 a { reversed a }\r\n }\r\n \r\n x <- new MyClass2\r\n pair (x method1) (x method2 \"sey\")\r\n ";
assertEqualsVerbose(pair("I'm here", "yes"), __2.runScript(src));
src = "\r\n class MyClass3 {\r\n a: String\r\n \r\n def getA { this a } // requiring the this keyword for now\r\n def setA a { this a <- a }\r\n def aLength { (this a) length }\r\n }\r\n \r\n x <- new MyClass3\r\n x setA \"abc\"\r\n assertEquals (x aLength) 3\r\n x getA\r\n ";
assertEqualsVerbose("abc", __2.runScript(src));
classSrc = "\r\n class MyClass4 {\r\n a: java.util.List\r\n }\r\n ";
c = (Class) __2.runScript(classSrc);
assertEqualsVerbose(fieldType(c, "a"), List.class);
classSrc = "\r\n class MyClass5 {\r\n a: L\r\n }\r\n ";
c = (Class) __2.runScript(classSrc);
assertEqualsVerbose("Raw type of L field", fieldType(c, "a"), List.class);
assertEqualsVerbose("Generic type of L field", genericFieldType(c, "a"), new ParameterizedTypeImpl(null, List.class, String.class));
classSrc = "\r\n class MyClass6 {\r\n x: int\r\n }\r\n ";
c = (Class) __2.runScript(classSrc);
assertEqualsVerbose(fieldType(c, "x"), int.class);
classSrc = "\r\n class ToString {\r\n def toString : S { \"It's me, George!\" }\r\n }\r\n new ToString\r\n ";
assertEqualsVerbose("It's me, George!", str(__2.runScript(classSrc)));
classSrc = "\r\n class MyClass7 {\r\n x: int[]\r\n }\r\n ";
c = (Class) __2.runScript(classSrc);
assertEqualsVerbose(fieldType(c, "x"), int[].class);
classSrc = " class Bla is IF0 { def get { \"hello\" } }\r\n new Bla ";
IF0 f = (IF0) (__2.runScript(classSrc));
assertEqualsVerbose("hello", f.get());
assertEqualsVerbose(Class.class, __2.runScript("\r\n _getClass2 class A { }\r\n "));
assertEqualsVerbose(5, __2.runScript("\r\n class MyClass8 {\r\n x: int\r\n \r\n ctor { this x <- 5 }\r\n }\r\n \r\n new MyClass8, x\r\n "));
assertEqualsVerbose(7, __2.runScript("\r\n class MyClass9 {\r\n x: int <- 7\r\n }\r\n \r\n new MyClass9, x\r\n "));
cl.rememberClassBytes(true);
cl.onClassDefined(__4 -> disassembleClass(__4));
classSrc = "\r\n class A { def yo { \"yay\" } }\r\n class B extends A { def wow { joinWithSpace (this yo) \"amazing!\" } }\r\n new B, wow\r\n ";
assertEqualsVerbose("yay amazing!", __2.runScript(classSrc));
classSrc = "\r\n class B extends test_leftArrowScript_classDefs_Base {\r\n def wow { joinWithSpace (this hey) (this hey) (this hey) } }\r\n new B, wow\r\n ";
assertEqualsVerbose("ho ho ho", __2.runScript(classSrc));
__2.runScript("\r\n class MyClass9 {\r\n x: int\r\n initializer { this x <- 5 }\r\n }\r\n \r\n assertEqualsVerbose 5 < new MyClass9, x\r\n ");
__2.runScript("\r\n class MyClass10 {\r\n l: L <- new ArrayList\r\n initializer { this l, add \"init\" }\r\n ctor { this l, add \"ctor\" }\r\n }\r\n \r\n assertEqualsVerbose (ll \"init\" \"ctor\") < new MyClass10, l\r\n ");
__2.runScript("\r\n class MyClassSelf {\r\n def me: MyClassSelf { this }\r\n }\r\n ");
__2.runScript("\r\n class ArgTypes {\r\n def doIt (s: S) { \"a string\" }\r\n def doIt (s: O) { \"not a string\" }\r\n }\r\n \r\n assertEqualsVerbose \"a string\" < new ArgTypes, doIt \"yo\"\r\n assertEqualsVerbose \"not a string\" < new ArgTypes, doIt 123\r\n ");
__2.runScript("\r\n class PrimReturn {\r\n def theNumber: int { 123 }\r\n }\r\n \r\n assertEqualsVerbose 123 < new PrimReturn, theNumber\r\n assertEqualsVerbose \"int\" < str < findMethod (new PrimReturn) \"theNumber\", getReturnType\r\n ");
__2.runScript("\r\n class Settable {\r\n settable x: int\r\n settable b: bool\r\n settable l: long\r\n settable d: double\r\n settable y: S\r\n }\r\n \r\n s <- new Settable, x 5, y \"test\", b true\r\n assertEqualsVerbose 5 < s x\r\n assertEqualsVerbose 5 < call s \"x\"\r\n assertEqualsVerbose \"test\" < s y\r\n assertEqualsVerbose \"test\" < call s \"y\"\r\n assertEqualsVerbose true < s b\r\n ");
__2.runScript("\r\n class Settable {\r\n settable s: S <- \"hello\"\r\n }\r\n \r\n assertEqualsVerbose \"hello\" < new Settable, s\r\n ");
__2.runScript("\r\n class SelfTypeTest {\r\n def me: selfType { this }\r\n }\r\n \r\n t <- new SelfTypeTest\r\n assertEqualsVerbose t < t me\r\n ");
__2.runScript("\r\n class VoidMethodTest is Closeable {\r\n def close: void {}\r\n }\r\n ");
Object o = __2.runScript("\r\n class TransientTest {\r\n transient i: int\r\n }\r\n new TransientTest\r\n ");
assertTrueVerbose("transient", isTransient(fieldObject(o, "i")));
o = __2.runScript("\r\n class LSTest {\r\n l: LS\r\n }\r\n new LSTest\r\n ");
assertEqualsVerbose("java.util.List", str(genericFieldType(o, "l")));
o = __2.runScript("\r\n class MyClass {}\r\n MyClass\r\n ");
assertContainsVerbose("MyClass", className((Class) o));
o = __2.runScript("\r\n class MyClass {\r\n static hello: S <- \"world\"\r\n }\r\n ");
assertEqualsVerbose("world", get((Class) o, "hello"));
}
static public void test_leftArrowScript_forIterator() {
IterableIterator> it = (IterableIterator>) (leftArrowVerbose(" for iterator i in ll 2 3 { pair i (nanoTime) }"));
assertTrue(it.hasNext());
long time = nanoTime();
sleep(1);
var p = it.next();
assertEquals(2, p.a);
assertTrue(p.b > time);
time = p.b;
sleep(1);
assertTrue(it.hasNext());
p = it.next();
assertEquals(3, p.a);
assertTrue(p.b > time);
assertFalse(it.hasNext());
IterableIterator it2 = (IterableIterator) (leftArrowVerbose(" for nested i in ll 2 3 { ll i (neg i) }"));
assertEqualsVerbose(ll(2, -2, 3, -3), asList(it2));
it2 = (IterableIterator) leftArrowVerbose("\r\n for nested i in ll 2 3 4 {\r\n if eq i 3 { continue }\r\n ll i (neg i)\r\n }\r\n ");
assertEqualsVerbose(ll(2, -2, 4, -4), asList(it2));
}
static public void assertFailVerbose(Runnable r) {
assertFail_verbose(r);
}
static public GazelleV_LeftArrowScript.Script leftArrowParse(String script) {
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
parser.allowTheWorld();
return parser.parse(script);
}
static public void test_leftArrowScript_comma() {
new TestFunctionValues(__1 -> leftArrowVerbose(__1)).io(" new Pair 1 2, a ", 1).io(" new Pair 1 2,\r\n a ", 1).run();
}
static public void test_leftArrowScript_antiComma() {
new TestFunctionValues(__1 -> leftArrowVerbose(__1)).io(" ll < plus 1 2 ", ll(3)).io(" ll < ll 5 6, size ", ll(2)).io(" v <- new Var < new Pair\r\n v get ", pair(null, null)).run();
}
static public void test_leftArrowScript_returnValueNotNeededOptimization() {
List tok = javaTokForStructure(sfu(leftArrowParse("for y to 2 { for x to 2 { y } }; null")));
assertFalse("test_leftArrowScript_returnValueNotNeededOptimization", !jcontains(tok, "returnValueNeeded=t"));
}
static public GazelleV_LeftArrowScript.Script leftArrowParseVerbose(String script) {
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
enableScaffolding(parser);
parser.allowTheWorld();
var parsedScript = parser.parse(script);
print("leftArrowParseVerbose:\n" + GazelleV_LeftArrowScript.indentedScriptStruct(parsedScript));
return parsedScript;
}
static public int l(Object[] a) {
return a == null ? 0 : a.length;
}
static public int l(boolean[] a) {
return a == null ? 0 : a.length;
}
static public int l(byte[] a) {
return a == null ? 0 : a.length;
}
static public int l(short[] a) {
return a == null ? 0 : a.length;
}
static public int l(long[] a) {
return a == null ? 0 : a.length;
}
static public int l(int[] a) {
return a == null ? 0 : a.length;
}
static public int l(float[] a) {
return a == null ? 0 : a.length;
}
static public int l(double[] a) {
return a == null ? 0 : a.length;
}
static public int l(char[] a) {
return a == null ? 0 : a.length;
}
static public int l(Collection c) {
return c == null ? 0 : c.size();
}
static public int l(Iterator i) {
return iteratorCount_int_close(i);
}
static public int l(Map m) {
return m == null ? 0 : m.size();
}
static public int l(CharSequence s) {
return s == null ? 0 : s.length();
}
static public long l(File f) {
return f == null ? 0 : f.length();
}
static public int l(IMultiSet ms) {
return ms == null ? 0 : ms.size();
}
static public int l(IMultiMap mm) {
return mm == null ? 0 : mm.size();
}
static public int l(IntRange r) {
return r == null ? 0 : r.length();
}
static public int l(IntSize o) {
return o == null ? 0 : o.size();
}
static public A firstKey(Map map) {
return first(keys(map));
}
static public A firstKey(IMultiMap map) {
return map == null ? null : first(map.keySet());
}
static public B firstValue(Map map) {
return first(values(map));
}
static public B firstValue(MultiSetMap map) {
return map == null ? null : first(firstValue(map.data));
}
static public B firstValue(MultiMap map) {
return map == null ? null : first(firstValue(map.data));
}
static public void test_leftArrowScript_magicSwitch() {
var test = new TestFunctionValues(__1 -> leftArrowVerbose(__1));
test.io("1 plus 2", 3).runAndClear();
test.io("userDir, f2s", f2s(userDir())).runAndClear();
}
static public class test_leftArrowScript_tilde_GetOptImpl {
public Object getOpt(String key) {
return key + "!";
}
}
static public void test_leftArrowScript_tilde() {
var test = new TestFunctionValues(__1 -> leftArrowVerbose(__1));
test.io("litmap \"a\" 2 \"b\" 3, ~a", 2).io("litmap \"a\" 2 \"b\" 3, ~b", 3).io("litmap \"a\" 2 \"b\" 3, ~c", null).io("litmap \"a\" (litmap \"x\" 2) \"b\" 3, ~a ~x", 2).runAndClear();
test.io("ll \"a\" \"b\", ~0", "a").io("ll \"a\" \"b\", ~1", "b").io("ll \"a\" \"b\", ~2", null).runAndClear();
test.io("def bla { litmap \"a\" 2 }\r\n bla~a", 2).runAndClear();
test.io(replaceIdentifiers("new GetOptImpl, ~hey", "GetOptImpl", className(test_leftArrowScript_tilde_GetOptImpl.class)), "hey!").runAndClear();
test.io("null, ~bla", null).runAndClear();
}
static public void test_leftArrowScript_then() {
new TestFunctionValues(__1 -> leftArrowVerbose(__1)).io(" new Pair 1 2, b 3 then b ", 3).run();
}
static public void assertInstanceOf(Class type, Object o) {
assertIsInstance(type, o);
}
static public void assertInstanceOf(Object o, Class type) {
assertInstanceOf(type, o);
}
static public Object leftArrow(String script) {
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
parser.allowTheWorld();
return parser.parse(script).get();
}
static public Object leftArrow(GazelleV_LeftArrowScriptParser parser, String script) {
return parser.parse(script).get();
}
static public void test_leftArrowScript_pcall() {
List errors = new ArrayList();
AutoCloseable __1 = tempSetPCallPolicyForThread(e -> errors.add(e));
try {
assertNullVerbose(leftArrowScript("\r\n pcall { fail \"What\" }\r\n "));
assertEqualsVerbose(1, l(errors));
assertContainsVerbose("What", str(first(errors)));
} finally {
_close(__1);
}
}
static public void test_leftArrowScript_ifdef() {
String src = "1 ifdef bla plus 1 endifdef";
assertEqualsVerbose(1, leftArrowVerbose(src));
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
parser.setFlag("bla");
assertEqualsVerbose(2, leftArrowVerbose(parser, src));
}
static public List replace(List l, A a, A b) {
for (int i = 0; i < l(l); i++) if (eq(l.get(i), a))
l.set(i, b);
return l;
}
static public List replace(A a, A b, List l) {
return replace(l, a, b);
}
static public String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
static public String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
static public String className(Object o) {
return getClassName(o);
}
static public void test_leftArrowScript_scriptError() {
Throwable error = (Throwable) (leftArrow("getException < Runnable fail"));
var scriptError = innerExceptionOfType(GazelleV_LeftArrowScript.ScriptError.class, error);
assertNotNullVerbose(scriptError);
}
static public class test_leftArrowScript_objectScope_Class1 {
public String hello(String x) {
return "hello " + x;
}
}
static public void test_leftArrowScript_objectScope() {
test_leftArrowScript_objectScope(new LASMultiClassLoader(mc()));
}
static public void test_leftArrowScript_objectScope(LASMultiClassLoader cl) {
String classPrefix = "scriptClasses.";
final class _C_1 {
public Object runScript(String code) {
var parser = enableScaffolding(new GazelleV_LeftArrowScriptParser().classDefPrefix(classPrefix).lasClassLoader(cl));
return leftArrowVerbose(parser, code);
}
}
final _C_1 __2 = new _C_1();
assertEqualsVerbose(10, __2.runScript("\r\n class X {\r\n i: int <- 5\r\n \r\n def j { i plus i }\r\n }\r\n \r\n new X, j\r\n "));
assertEqualsVerbose(10, __2.runScript("\r\n class X {\r\n i: int <- 5\r\n }\r\n \r\n class Y extends X {\r\n def j { i plus i }\r\n }\r\n \r\n new Y, j\r\n "));
assertEqualsVerbose(14, __2.runScript("\r\n class X {\r\n i: int <- 5\r\n \r\n def j { i: int <- 7; i plus i }\r\n }\r\n \r\n new X, j\r\n "));
assertEqualsVerbose(10, __2.runScript("\r\n class X {\r\n i: int\r\n \r\n def j { i <- 10; this }\r\n }\r\n \r\n new X, j, i\r\n "));
assertEqualsVerbose(10, __2.runScript("\r\n class X { i: int }\r\n \r\n class Y extends X {\r\n def j { i <- 10; this }\r\n }\r\n \r\n new Y, j, i\r\n "));
assertEqualsVerbose(2, __2.runScript("\r\n class X {\r\n i: int <- 1\r\n \r\n def yo { i <- i plus 1 }\r\n def j { yo; i }\r\n }\r\n \r\n new X, j\r\n "));
assertEqualsVerbose(6, __2.runScript("\r\n class X {\r\n def yo n { 1 plus n }\r\n def j { yo < 5 }\r\n }\r\n \r\n new X, j\r\n "));
assertEqualsVerbose(ll("o", "o"), __2.runScript(" \r\n class X {\r\n bla: S <- \"o\"\r\n def bla { \"x\" }\r\n def y { ll bla bla }\r\n }\r\n new X, y\r\n "));
assertEqualsVerbose(2, __2.runScript("\r\n class X {\r\n i: int <- 1\r\n \r\n def yo { i <- i plus 1 }\r\n }\r\n \r\n class Y extends X {\r\n def j { yo; i }\r\n }\r\n \r\n new Y, j\r\n "));
assertEqualsVerbose(6, __2.runScript("\r\n class X {\r\n i: int <- 1\r\n \r\n def yo x { i <- i plus x; this }\r\n def j { yo 5, i }\r\n }\r\n \r\n new X, j\r\n "));
assertEqualsVerbose(6, __2.runScript("\r\n class X {\r\n i: int <- 1\r\n \r\n def yo x { i <- i plus x; this }\r\n def j { (yo < 5) i }\r\n }\r\n \r\n new X, j\r\n "));
assertEqualsVerbose("hello world", __2.runScript(replaceIdentifiers("\r\n class X extends Class1 {\r\n def yo { hello \"world\" }\r\n }\r\n \r\n new X, yo\r\n ", "Class1", className(test_leftArrowScript_objectScope_Class1.class))));
assertEqualsVerbose(6, __2.runScript("\r\n class X {\r\n i: int <- 5\r\n \r\n initializer {\r\n i <- i plus 1\r\n }\r\n }\r\n \r\n new X, i\r\n "));
assertEqualsVerbose(3, __2.runScript("\r\n class X {\r\n i: int <- 3\r\n \r\n def j { var i <- 5; i <- i plus 1; this }\r\n }\r\n \r\n new X, j, i\r\n "));
}
static public void test_leftArrowScript_doWhile() {
String script = "\r\n sum <- 0\r\n do {\r\n sum <- sum plus 1\r\n } while { lessThan sum N }\r\n sum\r\n ";
assertEqualsVerbose(5, leftArrowVerbose(jreplace(script, "N", "5")));
assertEqualsVerbose(1, leftArrowVerbose(jreplace(script, "N", "0")));
}
static public String intern(String s) {
return fastIntern(s);
}
static volatile public StringBuffer local_log = new StringBuffer();
static public boolean printAlsoToSystemOut = true;
static volatile public Appendable print_log = local_log;
static volatile public int print_log_max = 1024 * 1024;
static volatile public int local_log_max = 100 * 1024;
static public boolean print_silent = false;
static public Object print_byThread_lock = new Object();
static volatile public ThreadLocal print_byThread;
static volatile public Object print_allThreads;
static volatile public Object print_preprocess;
static public void print() {
print("");
}
static public A print(String s, A o) {
print(combinePrintParameters(s, o));
return o;
}
static public A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = o + "\n";
print_noNewLine(s);
return o;
}
static public void print_noNewLine(String s) {
try {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
} catch (Throwable e) {
System.out.println(getStackTrace(e));
}
print_raw(s);
}
static public 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 public void print_autoRotate() {
}
static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public Method findMethod_cached(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
_MethodCache cache = callOpt_getCache((Class) o);
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
return m;
return null;
} else {
_MethodCache cache = callOpt_getCache(o.getClass());
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (findMethod_checkArgs(m, args, false))
return m;
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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 public Map> callF_cache = newDangerousWeakHashMap();
static public A callF(F0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
static public B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF(A a, IF1 f) {
return f == null ? null : f.get(a);
}
static public C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
static public void callF(A a, IVF1 f) {
if (f != null)
f.get(a);
}
static public void callF(IVF1 f, A a) {
if (f != null)
f.get(a);
}
static public Object callF(Runnable r) {
{
if (r != null)
r.run();
}
return null;
}
static public Object callF(Object f, Object... args) {
return safeCallF(f, args);
}
static public 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));
}
static public 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 public RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public char[] asChars(String s) {
return s == null ? null : s.toCharArray();
}
static public Duration msToDuration(double ms) {
return Duration.ofNanos(lround(msToNanos(ms)));
}
static public long daysToMS(double days) {
return round(days * 24 * 60 * 60 * 1000);
}
static public double[] cloneDoubleArray(double[] a) {
if (a == null)
return null;
double[] b = new double[a.length];
System.arraycopy(a, 0, b, 0, a.length);
return b;
}
static public BigInteger bigint(String s) {
return new BigInteger(s);
}
static public BigInteger bigint(long l) {
return BigInteger.valueOf(l);
}
static public int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static public int parseInt(char c) {
return Integer.parseInt(str(c));
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static public byte[] cloneByteArray(byte[] a) {
if (a == null)
return null;
byte[] b = new byte[a.length];
System.arraycopy(a, 0, b, 0, a.length);
return b;
}
static public boolean empty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean empty(Iterable c) {
return c == null || !c.iterator().hasNext();
}
static public boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean empty(Map map) {
return map == null || map.isEmpty();
}
static public boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static public boolean empty(BitSet bs) {
return bs == null || bs.isEmpty();
}
static public 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 public boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
static public boolean empty(double[] a) {
return a == null || a.length == 0;
}
static public boolean empty(float[] a) {
return a == null || a.length == 0;
}
static public boolean empty(int[] a) {
return a == null || a.length == 0;
}
static public boolean empty(long[] a) {
return a == null || a.length == 0;
}
static public boolean empty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean empty(short[] a) {
return a == null || a.length == 0;
}
static public boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
static public boolean empty(IMultiMap mm) {
return mm == null || mm.size() == 0;
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public boolean empty(IntRange r) {
return r == null || r.empty();
}
static public boolean empty(Rect r) {
return !(r != null && r.w != 0 && r.h != 0);
}
static public boolean empty(Chain c) {
return c == null;
}
static public boolean empty(AppendableChain c) {
return c == null;
}
static public boolean empty(IntSize l) {
return l == null || l.size() == 0;
}
static public ArrayList emptyList() {
return new ArrayList();
}
static public ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
static public ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static public ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
static public ArrayList emptyList(Class c) {
return new ArrayList();
}
static public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(char[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (var i : a) l.add(i);
return l;
}
static public ArrayList asList(byte[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (var i : a) l.add(i);
return l;
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(long[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static public ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static public ArrayList asList(double[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static public ArrayList asList(short[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (short i : a) l.add(i);
return l;
}
static public ArrayList asList(Iterator it) {
ArrayList l = new ArrayList();
if (it != null)
while (it.hasNext()) l.add(it.next());
return l;
}
static public ArrayList asList(IterableIterator s) {
return asList((Iterator) s);
}
static public 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 public ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null)
while ((a = p.next()) != null) l.add(a);
return l;
}
static public ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public ArrayList asList(ReverseChain c) {
return c == null ? emptyList() : c.toList();
}
static public List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
static volatile public boolean sleep_noSleep = false;
static public void sleep(long ms) {
ping();
if (ms < 0)
return;
if (isAWTThread() && ms > 100)
throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public void sleep() {
try {
if (sleep_noSleep)
throw fail("nosleep");
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public long round(double d) {
return Math.round(d);
}
static public String round(String s) {
return roundBracket(s);
}
static public Complex round(Complex c) {
return new Complex(round(c.re), round(c.im));
}
static public List reversedList(Iterable l) {
List x = cloneList(l);
Collections.reverse(x);
return x;
}
static public String reversedString(String s) {
return reverseString(s);
}
static public String shortClassName_dropNumberPrefix(Object o) {
return dropNumberPrefix(shortClassName(o));
}
static public RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
static public Object swing(Object f) {
return swingAndWait(f);
}
static public void swing(Runnable f) {
swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public void removeFromParent(final Component c) {
if (c != null) {
swing(() -> {
Container cc = c.getParent();
if (cc != null) {
cc.remove(c);
revalidate(cc);
}
});
}
}
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 public String join(Iterable strings) {
return join("", strings);
}
static public String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static public String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static public Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array) if (o != null)
set.add(o);
return set;
}
static public Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array) if (o != null)
set.add(o);
return set;
}
static public Set asSet(Iterable l) {
if (l instanceof Set)
return (Set) l;
HashSet set = new HashSet();
for (A o : unnull(l)) if (o != null)
set.add(o);
return set;
}
static public Set asSet(MultiSet ms) {
return ms == null ? null : ms.asSet();
}
static public String unnull(String s) {
return s == null ? "" : s;
}
static public Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static public List unnull(List l) {
return l == null ? emptyList() : l;
}
static public int[] unnull(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnull(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnull(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public float[] unnull(float[] l) {
return l == null ? emptyFloatArray() : l;
}
static public Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static public Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static public A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnull(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public int unnull(Integer i) {
return i == null ? 0 : i;
}
static public long unnull(Long l) {
return l == null ? 0L : l;
}
static public double unnull(Double l) {
return l == null ? 0.0 : l;
}
static public Complex complex(double re, double im) {
return new Complex(re, im);
}
static public Complex complex(double re) {
return new Complex(re, 0.0);
}
static public Complex complex(double[] reIm) {
if (empty(reIm))
return null;
if (l(reIm) != 2)
throw fail("Need 2 doubles to make complex number");
return complex(reIm[0], reIm[1]);
}
static public int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
static public int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public int cmp(int a, int b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public int cmp(long a, long b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public 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 public BufferedImage whiteImage(int w, int h) {
return newBufferedImage(w, h, Color.white);
}
static public BufferedImage whiteImage(int size) {
return whiteImage(size, size);
}
static public BufferedImage whiteImage(WidthAndHeight size) {
return whiteImage(size.getWidth(), size.getHeight());
}
static public BufferedImage bufferedImage(int[] pixels, int w, int h) {
return intArrayToBufferedImage(pixels, w, h);
}
static public BufferedImage bufferedImage(int[] pixels, WidthAndHeight size) {
return bufferedImage(pixels, size.getWidth(), size.getHeight());
}
static public BufferedImage bufferedImage(int w, int h, int[] pixels) {
return intArrayToBufferedImage(pixels, w, h);
}
static public BufferedImage bufferedImage(int w, int h) {
return newBufferedImage(w, h);
}
static public BufferedImage bufferedImage(int w, int h, RGB rgb) {
return newBufferedImage(w, h, rgb);
}
static public BufferedImage bufferedImage(int w, Color color) {
return bufferedImage(w, w, color);
}
static public BufferedImage bufferedImage(int w, int h, Color color) {
return newBufferedImage(w, h, color);
}
static public BufferedImage bufferedImage(Pt p, Color color) {
return newBufferedImage(p, color);
}
static public BufferedImage bufferedImage(WidthAndHeight size, Color color) {
return newBufferedImage(size.w(), size.h(), color);
}
static public BufferedImage bufferedImage(Color color, WidthAndHeight size) {
return bufferedImage(size, color);
}
static public int random_incl(int min, int max) {
return random_incl(min, max, defaultRandomizer());
}
static public int random_incl(int min, int max, Random random) {
return random(min, max + 1, random);
}
static public int random_incl(int max) {
return random(0, max + 1);
}
static public Rect translateRect(int x, int y, Rect r) {
return translateRect(r, x, y);
}
static public Rect translateRect(Rect r, int x, int y) {
return r == null ? null : new Rect(r.x + x, r.y + y, r.w, r.h);
}
static public int random(int n) {
return random(n, defaultRandomGenerator());
}
static public int random(int n, Random r) {
return random(r, n);
}
static public long random(long n) {
return random(n, defaultRandomGenerator());
}
static public long random(long n, Random r) {
return random(r, n);
}
static public int random(Random r, int n) {
return n <= 0 ? 0 : getRandomizer(r).nextInt(n);
}
static public long random(Random r, long n) {
return n <= 0 ? 0 : getRandomizer(r).nextLong(n);
}
static public double random(double max) {
return random() * max;
}
static public double random() {
return defaultRandomGenerator().nextInt(100001) / 100000.0;
}
static public double random(double min, double max) {
return min + random() * (max - min);
}
static public int random(int min, int max) {
return min + random(max - min);
}
static public long random(long min, long max) {
return min + random(max - min);
}
static public int random(int min, int max, Random r) {
return random(r, min, max);
}
static public int random(Random r, int min, int max) {
return min + random(r, max - min);
}
static public A random(List l) {
return oneOf(l);
}
static public A random(Collection c) {
if (c instanceof List)
return random((List ) c);
int i = random(l(c));
return collectionGet(c, i);
}
static public int random(IntRange r) {
return random(r.start, r.end);
}
static public Pair random(Map map) {
return entryToPair(random(entries(map)));
}
static public ThreadLocal currentImage_var = new ThreadLocal();
static public BufferedImage currentImage() {
return currentImage_var.get();
}
static public void currentImage(BufferedImage img) {
currentImage_var.set(img);
}
static public int toInt(Object o) {
if (o == null)
return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt((String) o);
if (o instanceof Boolean)
return boolToInt((Boolean) o);
throw fail("woot not int: " + getClassName(o));
}
static public int toInt(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
static public Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static public Object getOpt(String field, Object o) {
return getOpt_cached(o, field);
}
static public 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);
}
}
static public 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 public 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 public boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static public boolean contains(Iterable it, Object a) {
if (it != null)
for (Object o : it) if (eq(a, o))
return true;
return false;
}
static public boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
static public boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static public boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static public boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static public boolean contains(Producer p, A a) {
if (p != null && a != null)
while (true) {
A x = p.next();
if (x == null)
break;
if (eq(x, a))
return true;
}
return false;
}
static public boolean contains(Rect r, Pt p) {
return rectContains(r, p);
}
static public String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
static public 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 public 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 public boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public boolean eq(Symbol a, String b) {
return eq(str(a), b);
}
static public String _userHome;
static public String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
static public File userHome(String path) {
return new File(userDir(), path);
}
static public long countPingCalls(Runnable r) {
AtomicLong counter = new AtomicLong();
{
tempPingSource(new PingSource(() -> {
incAtomicLong(counter);
return false;
}));
{
if (r != null)
r.run();
}
}
return counter.get();
}
static public void printVars(Object... params) {
printVars_str(params);
}
static public void assertTrue(Object o) {
if (!(eq(o, true)))
throw fail(str(o));
}
static public boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static public boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static public boolean assertTrue(Scorer scorer, boolean b) {
scorer.add(b);
return b;
}
static public void testFunctionValue(IF1 function, A in, B expected) {
String what = print(renderFunctionCall(str(function), in));
assertEqualsVerbose(what, expected, function.get(in));
}
static public 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 public int javaTok_n, javaTok_elements;
static public boolean javaTok_opt = false;
static public List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !regionMatches(s, j, "*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') {
++j;
break;
} else if (c2 == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || 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;
} else if (c == '[' && d == '[') {
do ++j; while (j < l && !regionMatches(s, j, "]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !regionMatches(s, j, "]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
static public Map javaTokForJFind_array_cache = synchronizedMRUCache(1000);
static public String[] javaTokForJFind_array(String s) {
String[] tok = javaTokForJFind_array_cache.get(s);
if (tok == null)
javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s))));
return tok;
}
static public int findCodeTokens(List tok, String... tokens) {
return findCodeTokens(tok, 1, false, tokens);
}
static public int findCodeTokens(List tok, boolean ignoreCase, String... tokens) {
return findCodeTokens(tok, 1, ignoreCase, tokens);
}
static public int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String... tokens) {
return findCodeTokens(tok, startIdx, ignoreCase, tokens, null);
}
static public HashSet findCodeTokens_specials = lithashset("*", "", "", "", "\\*");
static public int findCodeTokens_bails, findCodeTokens_nonbails;
static public interface findCodeTokens_Matcher {
public boolean get(String token);
}
static public int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) {
int end = tok.size() - tokens.length * 2 + 2, nTokens = tokens.length;
int i = startIdx | 1;
findCodeTokens_Matcher[] matchers = new findCodeTokens_Matcher[nTokens];
IContentsIndexedList2 indexedList = tok instanceof IContentsIndexedList2 ? (IContentsIndexedList2) tok : null;
TreeSet indices = null;
int indicesOfs = 0;
for (int j = 0; j < nTokens; j++) {
String p = tokens[j];
findCodeTokens_Matcher matcher;
if (p.equals("*"))
matcher = t -> true;
else if (p.equals(""))
matcher = t -> isQuoted(t);
else if (p.equals(""))
matcher = t -> isIdentifier(t);
else if (p.equals(""))
matcher = t -> isInteger(t);
else if (p.equals("\\*"))
matcher = t -> t.equals("*");
else if (ignoreCase)
matcher = t -> eqic(p, t);
else {
matcher = t -> t.equals(p);
if (indexedList != null) {
TreeSet indices2 = indexedList.indicesOf_treeSetOfHasIndex(p);
if (indices2 == null)
return -1;
if (indices == null || indices2.size() < indices.size()) {
indices = indices2;
indicesOfs = j;
}
}
}
matchers[j] = matcher;
}
if (indices != null) {
int min = i + indicesOfs * 2;
SortedSet tailSet = min == 1 ? indices : indices.tailSet(new HasIndex(min));
outer: for (HasIndex h : tailSet) {
int idx = h.idx - indicesOfs * 2;
if (idx >= end)
break;
for (int j = 0; j < nTokens; j++) try {
if (!matchers[j].get(tok.get(idx + j * 2)))
continue outer;
} catch (IndexOutOfBoundsException e) {
print("fct indicesOfs=" + indicesOfs + ", h=" + h + ", idx=" + idx);
throw e;
}
if (condition == null || checkTokCondition(condition, tok, idx - 1))
return idx;
}
return -1;
}
outer: for (; i < end; i += 2) {
for (int j = 0; j < nTokens; j++) if (!matchers[j].get(tok.get(i + j * 2)))
continue outer;
if (condition == null || checkTokCondition(condition, tok, i - 1))
return i;
}
return -1;
}
static public String jreplaceExpandRefs(String s, List tokref) {
if (!contains(s, '$'))
return s;
List tok = javaTok(s);
for (int i = 1; i < l(tok); i += 2) {
String t = tok.get(i);
if (t.startsWith("$") && isInteger(t.substring(1))) {
String x = tokref.get(-1 + parseInt(t.substring(1)) * 2);
tok.set(i, x);
} else if (t.equals("\\")) {
tok.set(i, "");
i += 2;
}
}
return join(tok);
}
static public void clearAllTokens(List tok) {
for (int i = 0; i < tok.size(); i++) tok.set(i, "");
}
static public void clearAllTokens(List tok, int i, int j) {
for (; i < j; i++) tok.set(i, "");
}
static public List reTok(List tok) {
replaceCollection(tok, javaTok(tok));
return tok;
}
static public List reTok(List tok, int i) {
return reTok(tok, i, i + 1);
}
static public List reTok(List tok, int i, int j) {
i = max(i & ~1, 0);
j = min(l(tok), j | 1);
if (i >= j)
return tok;
List t = javaTok(joinSubList(tok, i, j));
replaceListPart(tok, i, j, t);
return tok;
}
static public List reTok(List tok, IntRange r) {
if (r != null)
reTok(tok, r.start, r.end);
return tok;
}
static public Boolean trueOrNull(Boolean b) {
return eq(b, false) ? null : b;
}
static public String joinNemptiesWithColon(String... strings) {
return joinNempties(": ", strings);
}
static public String joinNemptiesWithColon(Collection strings) {
return joinNempties(": ", strings);
}
static public int identityHash(Object o) {
return identityHashCode(o);
}
static public Throwable assertFail(Runnable r) {
return assertFail("", r);
}
static public Throwable assertFail(String msg, Runnable r) {
try {
r.run();
} catch (Throwable e) {
silentException(e);
return e;
}
throw fail("No exception thrown" + (nempty(msg) ? " - " + msg : " by " + r));
}
static public A innerExceptionOfType(Class c, Throwable e) {
while (true) {
ping();
if (e == null)
return null;
if (isInstanceOf(e, c))
return (A) e;
e = e.getCause();
}
}
static public int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >>> 2));
}
static public int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static public A printIndentedStruct(A a) {
return printIndentedStruct("", a);
}
static public A printIndentedStruct(String prefix, A a) {
print(prefix, indentedStructureForUser(a));
return a;
}
static public A printIndentedStruct(A a, structure_Data data) {
return printIndentedStruct("", a, data);
}
static public A printIndentedStruct(String prefix, A a, structure_Data data) {
print(prefix, indentedStructureForUser(a, data));
return a;
}
static public boolean nempty(Collection c) {
return !empty(c);
}
static public boolean nempty(CharSequence s) {
return !empty(s);
}
static public boolean nempty(Object[] o) {
return !empty(o);
}
static public boolean nempty(byte[] o) {
return !empty(o);
}
static public boolean nempty(int[] o) {
return !empty(o);
}
static public boolean nempty(BitSet bs) {
return !empty(bs);
}
static public boolean nempty(Map m) {
return !empty(m);
}
static public boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static public boolean nempty(IMultiMap mm) {
return mm != null && mm.size() != 0;
}
static public boolean nempty(Object o) {
return !empty(o);
}
static public boolean nempty(IntRange r) {
return !empty(r);
}
static public boolean nempty(Rect r) {
return r != null && r.w != 0 && r.h != 0;
}
static public boolean nempty(MultiSet ms) {
return ms != null && !ms.isEmpty();
}
static public boolean nempty(IntSize l) {
return l != null && l.size() != 0;
}
static public String appendColonIfNempty(String s) {
return empty(s) ? "" : s + ": ";
}
static public void _close(AutoCloseable c) {
if (c != null)
try {
c.close();
} catch (Throwable e) {
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else
throw rethrow(e);
}
}
static public void assertStartsWith(List a, List b) {
if (!startsWith(a, b))
throw fail(a + " does not start with " + b);
}
static public void assertStartsWith(String a, String b) {
if (!startsWith(a, b))
throw fail(quote(a) + " does not start with " + quote(b));
}
static public Map getDeclaredFields_cache = newDangerousWeakHashMap();
static public 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 public Field getField(Object o, String field) {
if (o == null)
return null;
return setOpt_findField(_getClass(o), field);
}
static public Object getField(Field field, Object o) {
return fieldGet(field, o);
}
static public void assertNotSame(String msg, Object a, Object b) {
if (a == b)
throw fail(msg);
}
static public void assertNotSame(Object a, Object b) {
if (a == b)
throw fail();
}
static public Class fieldType(Object o, String field) {
Field f = getField(o, field);
return f == null ? null : f.getType();
}
static public Type genericFieldType(Object o, String field) {
Field f = getField(o, field);
return f == null ? null : f.getGenericType();
}
static public void disassembleClass(Object o) {
printClassByteCode(o);
}
static public Class disassembleClass(String name) {
Class c = classForName(name);
disassembleClass(c);
return c;
}
static public void assertTrueVerbose(Object o) {
assertEqualsVerbose(true, o);
}
static public void assertTrueVerbose(String msg, Object o) {
assertEqualsVerbose(msg, true, o);
}
static public boolean isTransient(Field f) {
return (f.getModifiers() & java.lang.reflect.Modifier.TRANSIENT) != 0;
}
static public Field fieldObject(Object o, String field) {
return findField2(o, field);
}
static public > C assertContainsVerbose(C c, A y) {
return assertContainsVerbose(null, c, y);
}
static public > C assertContainsVerbose(String msg, C c, A y) {
printVars("assertContainsVerbose", "msg", msg, "c", c, "y", y);
if (!contains(c, y))
throw fail((msg != null ? msg + ": " : "") + y + " not contained in " + c);
return c;
}
static public String assertContainsVerbose(String b, String a) {
printVars("assertContainsVerbose", "a", a, "b", b);
if (!contains(a, b))
throw fail(quote(b) + " not contained in " + quote(a));
return a;
}
static public A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static public A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
static public boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
static public 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 public Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static public 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 public 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 public 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 public 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 public Object get(String field, Object o) {
return get(o, field);
}
static public boolean get(BitSet bs, int idx) {
return bs != null && bs.get(idx);
}
static public A assertEquals(Object x, A y) {
return assertEquals("", x, y);
}
static public 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 public void assertEquals(Scorer scorer, Object x, Object y) {
assertEquals(scorer, "", x, y);
}
static public 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 public void assertFalse(Object o) {
if (!(eq(o, false)))
throw fail(str(o));
}
static public boolean assertFalse(boolean b) {
if (b)
throw fail("oops");
return b;
}
static public boolean assertFalse(String msg, boolean b) {
if (b)
throw fail(msg);
return b;
}
static public void assertFail_verbose(Runnable r) {
try {
r.run();
} catch (Throwable e) {
print("OK: " + getInnerMessage(silentException(e)));
return;
}
throw fail("No exception thrown!");
}
static public List javaTokForStructure(String s) {
return javaTok_noMLS(s);
}
static public String sfu(Object o) {
return structureForUser(o);
}
static public boolean jcontains(String s, String pat) {
return jfind(s, pat) >= 0;
}
static public boolean jcontains(List tok, String pat) {
return jfind(tok, pat) >= 0;
}
static public boolean jcontains(List tok, String pat, Object condition) {
return jfind(tok, pat, condition) >= 0;
}
static public 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 public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public Pair first(Map map) {
return mapEntryToPair(first(entrySet(map)));
}
static public 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 public A first(IterableIterator i) {
return first((Iterator ) i);
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public Character first(CharSequence s) {
return empty(s) ? null : s.charAt(0);
}
static public A first(Pair p) {
return p == null ? null : p.a;
}
static public A first(T3 t) {
return t == null ? null : t.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public Double first(double[] l) {
return empty(l) ? null : l[0];
}
static public A first(A[] l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(Iterable l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(IF1 pred, Iterable l) {
return firstThat(pred, l);
}
static public A first(AppendableChain a) {
return a == null ? null : a.element;
}
static public A first(IMultiSet a) {
return a == null ? null : first(a.keySet());
}
static public Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keys(Object map) {
return keys((Map) map);
}
static public Set keys(MultiSet ms) {
return ms == null ? null : ms.keySet();
}
static public Set keys(IMultiMap mm) {
return mm == null ? null : mm.keySet();
}
static public Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static public Collection values(Object map) {
return values((Map) map);
}
static public Collection values(MultiMap mm) {
return mm == null ? emptyList() : concatLists(values(mm.data));
}
static public String replaceIdentifiers(String text, Object... params) {
Map map = paramsToMap(params);
if (empty(map))
return text;
return mapCodeTokens_javaTok(text, t -> map.containsKey(t) ? str(map.get(t)) : t);
}
static public void assertIsInstance(Class type, Object o) {
if (!isInstance(type, o))
throw fail(_getClass(o) + " is not a subclass of " + type);
}
static public void assertIsInstance(Object o, Class type) {
assertIsInstance(type, o);
}
static public AutoCloseable tempSetPCallPolicyForThread(PCallPolicy policy) {
return tempSetTL(pcallPolicyForThread_tl(), policy);
}
static public A assertNullVerbose(A y) {
assertNullVerbose((String) null, y);
return y;
}
static public A assertNullVerbose(String msg, A y) {
if (y != null)
throw fail((msg != null ? msg + ": " : "expected null: ") + y);
print("OK: null");
return y;
}
static public Object leftArrowScript(String script) {
return leftArrow(script);
}
static public A assertNotNullVerbose(A y) {
assertNotNullVerbose((String) null, y);
return y;
}
static public A assertNotNullVerbose(String msg, A y) {
if (y == null) {
throw fail((msg != null ? msg + ": " : "") + "value is null");
} else
print("OK (not null): " + y);
return y;
}
static public Method fastIntern_method;
static public 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 public String combinePrintParameters(String s, Object o) {
return (endsWithLetterOrDigit(s) ? s + ": " : s) + o;
}
static public void ping_okInCleanUp() {
}
static public Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static public A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static public A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static public ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static public boolean isFalse(Object o) {
return eq(false, o);
}
static public String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static public String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static public String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static public String getStackTrace(String msg) {
return getStackTrace_noRecord(new Throwable(msg));
}
static public 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 public 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 public 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 public void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static public ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
static public AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
static final public Map callOpt_cache = newDangerousWeakHashMap();
static public Object callOpt_cached(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null)
return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public _MethodCache callOpt_getCache(Class c) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
static public boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static public Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
static public Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
static public 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 public 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 public Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static public Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static public Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static public void _handleError(Error e) {
}
static public long lround(double d) {
return Math.round(d);
}
static public long lround(Number n) {
return lround(toDouble(n));
}
static public double msToNanos(double ms) {
return ms * 1e6;
}
static public boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static public String getType(Object o) {
return getClassName(o);
}
static public long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static public long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static public int max(int a, int b) {
return Math.max(a, b);
}
static public int max(int a, int b, int c) {
return max(max(a, b), c);
}
static public long max(int a, long b) {
return Math.max((long) a, b);
}
static public long max(long a, long b) {
return Math.max(a, b);
}
static public double max(int a, double b) {
return Math.max((double) a, b);
}
static public float max(float a, float b) {
return Math.max(a, b);
}
static public double max(double a, double b) {
return Math.max(a, b);
}
static public > A max(Iterable l) {
A max = null;
var it = iterator(l);
if (it.hasNext()) {
max = it.next();
while (it.hasNext()) {
A a = it.next();
if (cmp(a, max) > 0)
max = a;
}
}
return max;
}
static public double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
static public short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
static public int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
static public > A max(A a, A b) {
return cmp(a, b) >= 0 ? a : b;
}
static public boolean ping() {
return ping(pingSource());
}
static public boolean ping(PingSource source) {
ping_v3(source);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
return ping();
}
static volatile public boolean ping_pauseAll = false;
static public boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
static public boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static public Object sleepQuietly_monitor = new Object();
static public void sleepQuietly() {
try {
assertFalse(isAWTThread());
synchronized (sleepQuietly_monitor) {
sleepQuietly_monitor.wait();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String roundBracket(String s) {
return "(" + s + ")";
}
static public String roundBracket(Object s) {
return roundBracket(str(s));
}
static public ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static public ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
static public String reverseString(String s) {
return empty(s) ? s : new StringBuilder(s).reverse().toString();
}
static public String dropNumberPrefix(String s) {
return dropFirst(s, indexOfNonDigit(s));
}
static public void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else {
r = addThreadInfoToRunnable(r);
executingSwingCode(r);
EventQueue.invokeAndWait(r);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object swingAndWait(Object f) {
if (isAWTThread())
return callF(f);
else {
Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
static public A revalidate(final A c) {
if (c == null || !c.isShowing())
return c;
{
swing(() -> {
c.revalidate();
c.repaint();
});
}
return c;
}
static public void revalidate(JFrame f) {
revalidate((Component) f);
}
static public void revalidate(JInternalFrame f) {
revalidate((Component) f);
}
static public String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static public int[] emptyIntArray_a = new int[0];
static public int[] emptyIntArray() {
return emptyIntArray_a;
}
static public char[] emptyCharArray = new char[0];
static public char[] emptyCharArray() {
return emptyCharArray;
}
static public double[] emptyDoubleArray = new double[0];
static public double[] emptyDoubleArray() {
return emptyDoubleArray;
}
static public float[] emptyFloatArray = new float[0];
static public float[] emptyFloatArray() {
return emptyFloatArray;
}
static public Map emptyMap() {
return new HashMap();
}
static public Object[] emptyObjectArray_a = new Object[0];
static public Object[] emptyObjectArray() {
return emptyObjectArray_a;
}
static public Symbol emptySymbol_value;
static public Symbol emptySymbol() {
if (emptySymbol_value == null)
emptySymbol_value = symbol("");
return emptySymbol_value;
}
static public BufferedImage newBufferedImage(int w, int h) {
return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}
static public BufferedImage newBufferedImage(int w, int h, RGB rgb) {
return newBufferedImage(w, h, rgb.getColor());
}
static public BufferedImage newBufferedImage(int w, int h, Color color) {
BufferedImage img = newBufferedImage(w, h);
Graphics2D g = img.createGraphics();
g.setColor(or(color, Color.white));
g.fillRect(0, 0, w, h);
return img;
}
static public BufferedImage newBufferedImage(Pt p, Color color) {
return newBufferedImage(p.x, p.y, color);
}
static public BufferedImage newBufferedImage(WidthAndHeight size, Color color) {
return newBufferedImage(size.w(), size.h(), color);
}
static public BufferedImage newBufferedImage(int w, int h, int[] pixels) {
return intArrayToBufferedImage(pixels, w, h);
}
static public BufferedImageWithMeta intArrayToBufferedImage(int[] pixels, int w) {
return intArrayToBufferedImage(pixels, w, pixels.length / w);
}
static public BufferedImageWithMeta intArrayToBufferedImage(int[] pixels, int w, int h) {
if (w == 0 || h == 0)
return null;
int[] bitMasks = new int[] { 0xFF0000, 0xFF00, 0xFF, 0xFF000000 };
SinglePixelPackedSampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, w, h, bitMasks);
DataBufferInt db = new DataBufferInt(pixels, pixels.length);
WritableRaster wr = Raster.createWritableRaster(sm, db, new Point());
return new BufferedImageWithMeta(ColorModel.getRGBdefault(), wr, false, null);
}
static public BufferedImageWithMeta intArrayToBufferedImage(int w, int... pixels) {
return intArrayToBufferedImage(pixels, w);
}
static public Random defaultRandomizer() {
return defaultRandomGenerator();
}
static public Random defaultRandomGenerator() {
{
Random r = customRandomizerForThisThread();
if (r != null)
return r;
}
return ThreadLocalRandom.current();
}
static public Random getRandomizer(Random r) {
return r != null ? r : defaultRandomGenerator();
}
static public A oneOf(List l) {
if (empty(l))
return null;
int n = l.size();
return n == 1 ? first(l) : l.get(defaultRandomizer().nextInt(n));
}
static public char oneOf(String s) {
return empty(s) ? '?' : s.charAt(random(l(s)));
}
static public A oneOf(A... l) {
return oneOf(asList(l));
}
static public A collectionGet(Collection c, int idx) {
if (c == null || idx < 0 || idx >= l(c))
return null;
if (c instanceof List)
return listGet((List ) c, idx);
Iterator it = c.iterator();
for (int i = 0; i < idx; i++) if (it.hasNext())
it.next();
else
return null;
return it.hasNext() ? it.next() : null;
}
static public Pair entryToPair(Map.Entry e) {
return mapEntryToPair(e);
}
static public Set> entries(Map map) {
return _entrySet(map);
}
static public int boolToInt(boolean b) {
return b ? 1 : 0;
}
static public class getOpt_Map extends WeakHashMap {
public getOpt_Map() {
if (getOpt_special == null)
getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final public Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
static public HashMap getOpt_special;
static public 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 public 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 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);
}
}
static public 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 public 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 public boolean rectContains(int x1, int y1, int w, int h, Pt p) {
return p.x >= x1 && p.y >= y1 && p.x < x1 + w && p.y < y1 + h;
}
static public boolean rectContains(Rect a, Rect b) {
return b.x >= a.x && b.y >= a.y && b.x2() <= a.x2() && b.y2() <= a.y2();
}
static public boolean rectContains(Rect a, Rectangle b) {
return rectContains(a, toRect(b));
}
static public boolean rectContains(Rect a, int x, int y) {
return a != null && a.contains(x, y);
}
static public boolean rectContains(Rect a, Pt p) {
return a != null && p != null && a.contains(p);
}
static public String actualUserHome_value;
static public String actualUserHome() {
if (actualUserHome_value == null) {
if (isAndroid())
actualUserHome_value = "/storage/emulated/0/";
else
actualUserHome_value = System.getProperty("user.home");
}
return actualUserHome_value;
}
static public File actualUserHome(String sub) {
return newFile(new File(actualUserHome()), sub);
}
static public AutoCloseable tempPingSource(PingSource source) {
return tempSetPingSource(source);
}
static public long incAtomicLong(AtomicLong l) {
return l.incrementAndGet();
}
static public void printVars_str(Object... params) {
print(renderVars_str(params));
}
static public String renderFunctionCall(String fname, Object... args) {
return formatFunctionCall(fname, args);
}
static public 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 public boolean regionMatches(String a, int offsetA, String b, int offsetB, int len) {
return a != null && b != null && a.regionMatches(offsetA, b, offsetB, len);
}
static public boolean regionMatches(String a, int offsetA, String b) {
return regionMatches(a, offsetA, b, 0, l(b));
}
static public String javaTok_substringN(String s, int i, int j) {
if (i == j)
return "";
if (j == i + 1 && s.charAt(i) == ' ')
return " ";
return s.substring(i, j);
}
static public String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
static public List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
}
static public Map synchronizedMRUCache(int maxSize) {
return synchroMap(new MRUCache(maxSize));
}
static public String[] codeTokensAsStringArray(List tok) {
int n = max(0, (l(tok) - 1) / 2);
String[] out = new String[n];
for (int i = 0; i < n; i++) out[i] = tok.get(i * 2 + 1);
return out;
}
static public int jfind(String s, String in) {
return jfind(javaTok(s), in);
}
static public int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
static public int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, (ITokCondition) null);
}
static public int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, String in, IIntPred condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, int startIndex, String in, IIntPred condition) {
return jfind(tok, startIndex, in, tokCondition(condition));
}
static public int jfind(List tok, String in, ITokCondition condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, int startIndex, String in, ITokCondition condition) {
return jfind(tok, startIndex, in, (Object) condition);
}
static public int jfind(List tok, int startIdx, String in, Object condition) {
return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
}
static public int jfind(List tok, List tokin) {
return jfind(tok, 1, tokin);
}
static public int jfind(List tok, int startIdx, List tokin) {
return jfind(tok, startIdx, tokin, null);
}
static public int jfind(List tok, int startIdx, String[] tokinC, Object condition) {
return findCodeTokens(tok, startIdx, false, tokinC, condition);
}
static public int jfind(List tok, int startIdx, List tokin, Object condition) {
return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
}
static public List jfind_preprocess(List tok) {
for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
return tok;
}
static public HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
static public boolean isQuoted(String s) {
if (isNormalQuoted(s))
return true;
return isMultilineQuoted(s);
}
static public boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static public 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 public boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(Symbol a, Symbol b) {
return eq(a, b);
}
static public boolean eqic(Symbol a, String b) {
return eqic(asString(a), b);
}
static public boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static public boolean checkTokCondition(Object condition, List tok, int i) {
if (condition instanceof TokCondition)
return ((TokCondition) condition).get(tok, i);
return checkCondition(condition, tok, i);
}
static public void replaceCollection(Collection dest, Collection src) {
if (dest == src)
return;
dest.clear();
if (src != null)
dest.addAll(src);
}
static public int min(int a, int b) {
return Math.min(a, b);
}
static public long min(long a, long b) {
return Math.min(a, b);
}
static public float min(float a, float b) {
return Math.min(a, b);
}
static public float min(float a, float b, float c) {
return min(min(a, b), c);
}
static public double min(double a, double b) {
return Math.min(a, b);
}
static public double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static public float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static public byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
static public short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
static public int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
static public > A min(A a, A b) {
return cmp(a, b) <= 0 ? a : b;
}
static public String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
static public String joinSubList(List l, int i) {
return join(subList(l, i));
}
static public String joinSubList(List l, IntRange r) {
return r == null ? null : joinSubList(l, r.start, r.end);
}
static public void replaceListPart(List l, int i, int j, List l2) {
replaceSublist(l, i, j, l2);
}
static public String joinNempties(String sep, Object... strings) {
return joinStrings(sep, strings);
}
static public String joinNempties(String sep, Iterable strings) {
return joinStrings(sep, strings);
}
static public int identityHashCode(Object o) {
return System.identityHashCode(o);
}
static volatile public int silentException_count;
static volatile public Throwable silentException_lastException;
static public Throwable silentException(Throwable e) {
++silentException_count;
lastException(e);
return silentException_lastException = e;
}
static public Throwable lastSilentException() {
return silentException_lastException;
}
static public boolean isInstanceOf(Object o, Class type) {
return type.isInstance(o);
}
static public String indentedStructureForUser(Object o) {
return indentedStructureForUser(Integer.MAX_VALUE, o);
}
static public String indentedStructureForUser(int levels, Object o) {
return indentStructureString(levels, structForUser(o));
}
static public String indentedStructureForUser(Object o, structure_Data data) {
return indentedStructureForUser(Integer.MAX_VALUE, o, data);
}
static public String indentedStructureForUser(int levels, Object o, structure_Data data) {
return indentStructureString(levels, structForUser(o, data));
}
static public boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static public boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static public 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 public 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 public 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 public void setOpt(Object o, String field, Object value) {
try {
if (o == null)
return;
Class c = o.getClass();
HashMap map;
if (getOpt_cache == null)
map = getOpt_makeCache(c);
else
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
setOpt_raw(o, field, value);
return;
}
Field f = map.get(field);
if (f != null) {
smartSet(f, o, value);
return;
}
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 public void setOpt(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public 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 public Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class _getClass(Object o) {
return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
}
static public Class _getClass(Object realm, String name) {
try {
return classLoaderForObject(realm).loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
static public Object fieldGet(Field f, Object o) {
try {
return f == null ? null : f.get(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void printClassByteCode(Object o) {
if (o == null)
return;
JavaClass clz = classToBCEL(o);
if (clz == null) {
print("No class data found for " + _getClass(o));
return;
}
print("PRINTING BYTE CODE FOR: " + assertEquals("Disassembled class name", className(o), clz.getClassName()));
print();
print(tabToSingleSpace(str(clz)));
print();
for (org.apache.bcel.classfile.Method method : clz.getMethods()) {
printWithNLBeforeAndAfter(method);
printWithIndent(tabToSingleSpace(str(method.getCode())));
}
print();
}
static public Map classForName_cache = synchroHashMap();
static public Class classForName(String name) {
return classForName(name, null);
}
static public Class classForName(String name, Object classFinder) {
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 public 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 public Field findField2(Object o, String field) {
Class c = o.getClass();
HashMap map;
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class)
return findField2_findStaticField((Class) o, field);
}
return map.get(field);
}
static public Field findField2_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 public Object getOptDynOnly(DynamicObject o, String field) {
if (o == null || o.fieldValues == null)
return null;
return o.fieldValues.get(field);
}
static public ThreadLocal assertVerbose_value = new ThreadLocal();
static public void assertVerbose(boolean b) {
assertVerbose_value.set(b);
}
static public boolean assertVerbose() {
return isTrue(assertVerbose_value.get());
}
static public String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
static public Map nullIfEmpty(Map map) {
return isEmpty(map) ? null : map;
}
static public List nullIfEmpty(List l) {
return isEmpty(l) ? null : l;
}
static public String getInnerMessage(Throwable e) {
if (e == null)
return null;
return getInnerException(e).getMessage();
}
static public List javaTok_noMLS(String s) {
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') {
++j;
break;
} else if (c2 == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
return tok;
}
static public String structureForUser(Object o) {
return structureForUser(o, new structure_Data());
}
static public String structureForUser(Object o, structure_Data d) {
d.noStringSharing = true;
d.warnIfUnpersistable(false);
return beautifyStructure(structure(o, d));
}
static public Pair mapEntryToPair(Map.Entry e) {
return e == null ? null : pair(e.getKey(), e.getValue());
}
static public Set> entrySet(Map map) {
return _entrySet(map);
}
static public A firstThat(Iterable l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(A[] l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static public A firstThat(IF1 pred, A[] l) {
return firstThat(l, pred);
}
static public List concatLists(Iterable ... lists) {
List l = new ArrayList();
if (lists != null)
for (Iterable list : lists) addAll(l, list);
return l;
}
static public List concatLists(Collection extends Iterable > lists) {
List l = new ArrayList();
if (lists != null)
for (Iterable list : lists) addAll(l, list);
return l;
}
static public 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 public String mapCodeTokens_javaTok(IF1 f, String s) {
return join(mapCodeTokens(f, javaTok_cached(s)));
}
static public String mapCodeTokens_javaTok(String s, IF1 f) {
return mapCodeTokens_javaTok(f, s);
}
static public boolean isInstance(Class type, Object arg) {
return type.isInstance(arg);
}
static public AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
static public AutoCloseable tempSetTL(BetterThreadLocal tl, A a) {
return tempSetThreadLocalIfNecessary(tl, a);
}
static public ThreadLocal pcallPolicyForThread_tl_tl = new ThreadLocal();
static public ThreadLocal pcallPolicyForThread_tl() {
return pcallPolicyForThread_tl_tl;
}
static public 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 public 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;
}
static public Class javax() {
return getJavaX();
}
static public void upgradeJavaXAndRestart() {
run("#1001639");
restart();
sleep();
}
static public boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
static public A or(A a, A b) {
return a != null ? a : b;
}
static volatile public PersistableThrowable lastException_lastException;
static public PersistableThrowable lastException() {
return lastException_lastException;
}
static public void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static public String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
static public 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 public String hideCredentials(Object o) {
return hideCredentials(str(o));
}
static public 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 public int indexOf(List l, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
static public int indexOf(List l, A a) {
if (l == null)
return -1;
return l.indexOf(a);
}
static public int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static public int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static public int indexOf(String a, char b) {
return a == null ? -1 : a.indexOf(b);
}
static public int indexOf(String a, int i, char b) {
return indexOf(a, b, i);
}
static public int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static public int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static public 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 public 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 public 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 public 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 public Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
static public void pcallFAll_minimalExceptionHandling(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
ping();
pcallF_minimalExceptionHandling(f, args);
}
}
static public void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) {
while (it.hasNext()) {
ping();
pcallF_minimalExceptionHandling(it.next(), args);
}
}
static public Set vm_busListeners_live_cache;
static public Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
static public Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static public Map vm_busListenersByMessage_live_cache;
static public Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
static public Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static public 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 public boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static public List _registerDangerousWeakMap_preList;
static public A _registerDangerousWeakMap(A map) {
return _registerDangerousWeakMap(map, null);
}
static public A _registerDangerousWeakMap(A map, Object init) {
callF(init, map);
if (init instanceof String) {
final String f = (String) init;
init = new VF1() {
public void get(Map map) {
try {
callMC(f, map);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callMC(f, map)";
}
};
}
if (javax() == null) {
if (_registerDangerousWeakMap_preList == null)
_registerDangerousWeakMap_preList = synchroList();
_registerDangerousWeakMap_preList.add(pair(map, init));
return map;
}
call(javax(), "_registerDangerousWeakMap", map, init);
return map;
}
static public void _onLoad_registerDangerousWeakMap() {
assertNotNull(javax());
if (_registerDangerousWeakMap_preList == null)
return;
for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b);
_registerDangerousWeakMap_preList = null;
}
static public Map synchroMap() {
return synchroHashMap();
}
static public Map synchroMap(Map map) {
return new SynchronizedMap(map);
}
static public Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static public String joinWithSpace(Iterable c) {
return join(" ", c);
}
static public String joinWithSpace(Object... c) {
return join(" ", c);
}
static public List classNames(Collection l) {
return getClassNames(l);
}
static public List classNames(Object[] l) {
return getClassNames(asList(l));
}
static public double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o instanceof String)
return parseDouble((String) o);
if (o == null)
return 0.0;
throw fail(o);
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public PingSource pingSource() {
return pingSource_tl().get();
}
static public PingSource pingSource(Thread thread) {
return pingSource_tl().get(thread);
}
static public boolean ping_v3() {
return ping_v3(pingSource());
}
static public boolean ping_v3(PingSource source) {
{
if (source != null)
source.get();
}
return true;
}
static public int isAndroid_flag;
static public boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
static public Boolean isHeadless_cache;
static public boolean isHeadless() {
if (isHeadless_cache != null)
return isHeadless_cache;
if (isAndroid())
return isHeadless_cache = true;
if (GraphicsEnvironment.isHeadless())
return isHeadless_cache = true;
try {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) {
return isHeadless_cache = true;
}
}
static public Object collectionMutex(List l) {
return l;
}
static public Object collectionMutex(Object o) {
if (o instanceof List)
return o;
String c = className(o);
return o;
}
static public String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
static public String[] dropFirst(String[] a) {
return drop(1, a);
}
static public Object[] dropFirst(Object[] a) {
return drop(1, a);
}
static public List dropFirst(List l) {
return dropFirst(1, l);
}
static public List dropFirst(int n, Iterable i) {
return dropFirst(n, toList(i));
}
static public List dropFirst(Iterable i) {
return dropFirst(toList(i));
}
static public List dropFirst(int n, List l) {
return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
static public List dropFirst(List l, int n) {
return dropFirst(n, l);
}
static public String dropFirst(int n, String s) {
return substring(s, n);
}
static public String dropFirst(String s, int n) {
return substring(s, n);
}
static public String dropFirst(String s) {
return substring(s, 1);
}
static public Chain dropFirst(Chain c) {
return c == null ? null : c.next;
}
static public int indexOfNonDigit(String s) {
int n = l(s);
for (int i = 0; i < n; i++) if (!isDigit(s.charAt(i)))
return i;
return -1;
}
static public Runnable addThreadInfoToRunnable(final Object r) {
final Object info = _threadInfo();
return info == null ? asRunnable(r) : new Runnable() {
public void run() {
try {
_inheritThreadInfo(info);
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_inheritThreadInfo(info); callF(r);";
}
};
}
static transient public Set> onExecutingSwingCode;
public static void onExecutingSwingCode(IVF1 f) {
onExecutingSwingCode = createOrAddToSyncLinkedHashSet(onExecutingSwingCode, f);
}
public static void removeExecutingSwingCodeListener(IVF1 f) {
main.remove(onExecutingSwingCode, f);
}
public static void executingSwingCode(Runnable code) {
if (onExecutingSwingCode != null)
for (var listener : onExecutingSwingCode) pcallF_typed(listener, code);
}
static public WeakHasherMap symbol_map = new WeakHasherMap(new Hasher() {
public int hashCode(Symbol symbol) {
return symbol.text.hashCode();
}
public boolean equals(Symbol a, Symbol b) {
if (a == null)
return b == null;
return b != null && eq(a.text, b.text);
}
});
static public Symbol symbol(String s) {
if (s == null)
return null;
synchronized (symbol_map) {
Symbol symbol = new Symbol(s, true);
Symbol existingSymbol = symbol_map.findKey(symbol);
if (existingSymbol == null)
symbol_map.put(existingSymbol = symbol, true);
return existingSymbol;
}
}
static public Symbol symbol(CharSequence s) {
if (s == null)
return null;
if (s instanceof Symbol)
return (Symbol) s;
if (s instanceof String)
return symbol((String) s);
return symbol(str(s));
}
static public Symbol symbol(Object o) {
return symbol((CharSequence) o);
}
static public Random customRandomizerForThisThread() {
return customRandomizerForThisThread_tl().get();
}
static public A listGet(List l, int idx) {
return l != null && idx >= 0 && idx < l.size() ? l.get(idx) : null;
}
static public Set> _entrySet(Map map) {
return map == null ? Collections.EMPTY_SET : map.entrySet();
}
static public void clear(Collection c) {
if (c != null)
c.clear();
}
static public void clear(Map map) {
if (map != null)
map.clear();
}
static public void put(Map map, A a, B b) {
if (map != null)
map.put(a, b);
}
static public void put(List l, int i, A a) {
if (l != null && i >= 0 && i < l(l))
l.set(i, a);
}
static public B syncMapGet2(Map map, A a) {
if (map == null)
return null;
synchronized (collectionMutex(map)) {
return map.get(a);
}
}
static public B syncMapGet2(A a, Map map) {
return syncMapGet2(map, a);
}
static public boolean isSubtypeOf(Class a, Class b) {
return a != null && b != null && b.isAssignableFrom(a);
}
static public Set reflection_classesNotToScan_value = litset("jdk.internal.loader.URLClassPath");
static public Set reflection_classesNotToScan() {
return reflection_classesNotToScan_value;
}
static public Rect toRect(Rectangle r) {
return r == null ? null : new Rect(r);
}
static public Rect toRect(RectangularShape r) {
return r == null ? null : toRect(r.getBounds());
}
static public Rect toRect(Rect r) {
return r;
}
static public AutoCloseable tempSetPingSource(PingSource source) {
return tempSetTL_noInit(pingSource_tl(), source);
}
static public 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));
}
static public String formatFunctionCall(String fname, Object... args) {
return formatFunctionCall((Object) fname, args);
}
static public String formatFunctionCall(Object fname, Object... args) {
return fname + "(" + joinWithComma(allToString(args)) + ")";
}
static public String formatFunctionCall(String fname, Iterable args) {
return formatFunctionCall((Object) fname, args);
}
static public String formatFunctionCall(Object fname, Iterable args) {
return formatFunctionCall(fname, toObjectArray(args));
}
static public int lastIndexOf(String a, String b) {
return a == null || b == null ? -1 : a.lastIndexOf(b);
}
static public int lastIndexOf(String a, char b) {
return a == null ? -1 : a.lastIndexOf(b);
}
static public int lastIndexOf(List l, int i, A a) {
if (l == null)
return -1;
for (i = min(l(l), i) - 1; i >= 0; i--) if (eq(l.get(i), a))
return i;
return -1;
}
static public int lastIndexOf(List l, A a) {
if (l == null)
return -1;
for (int i = l(l) - 1; i >= 0; i--) if (eq(l.get(i), a))
return i;
return -1;
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public 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);
}
static public String substring(String s, IntRange r) {
return r == null ? null : substring(s, r.start, r.end);
}
static public String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
static public ITokCondition tokCondition(IIntPred condition) {
return condition == null ? null : (tok, nIdx) -> condition.get(nIdx);
}
static public ArrayList litlist(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
static public List replaceSublist(List l, List x, List y) {
if (x == null)
return l;
int i = 0;
while (true) {
i = indexOfSubList(l, x, i);
if (i < 0)
break;
replaceSublist(l, i, i + l(x), y);
i += l(y);
}
return l;
}
static public List replaceSublist(List l, int fromIndex, int toIndex, List y) {
int n = y.size(), toIndex_new = fromIndex + n;
if (toIndex_new < toIndex) {
removeSubList(l, toIndex_new, toIndex);
copyListPart(y, 0, l, fromIndex, n);
} else {
copyListPart(y, 0, l, fromIndex, toIndex - fromIndex);
if (toIndex_new > toIndex)
l.addAll(toIndex, subList(y, toIndex - fromIndex));
}
return l;
}
static public List replaceSublist(List l, IntRange r, List y) {
return replaceSublist(l, r.start, r.end, y);
}
static public boolean isNormalQuoted(String s) {
int l = l(s);
if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"'))
return false;
int j = 1;
while (j < l) if (s.charAt(j) == '"')
return j == l - 1;
else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
return false;
}
static public boolean isMultilineQuoted(String s) {
if (!startsWith(s, "["))
return false;
int i = 1, n = s.length();
while (i < n && s.charAt(i) == '=') ++i;
return i < n && s.charAt(i) == '[';
}
static public 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 public String asString(Object o) {
return o == null ? null : o.toString();
}
static public boolean checkCondition(Object condition, Object... args) {
return isTrue(callF(condition, args));
}
static public boolean checkCondition(IF1 condition, A arg) {
return isTrue(callF(condition, arg));
}
static public List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static public List subList(int startIndex, List l) {
return subList(l, startIndex);
}
static public List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static public 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 public List subList(List l, IntRange r) {
return subList(l, r.start, r.end);
}
static public String joinStrings(String sep, Object... strings) {
return joinStrings(sep, Arrays.asList(strings));
}
static public String joinStrings(String sep, Iterable strings) {
StringBuilder buf = new StringBuilder();
for (Object o : unnull(strings)) {
String s = strOrNull(o);
if (nempty(s)) {
if (nempty(buf))
buf.append(sep);
buf.append(s);
}
}
return str(buf);
}
static public String indentStructureString(String s) {
return indentStructureString(100, s);
}
static public String indentStructureString(int levels, String s) {
if (s == null)
return null;
return new StructureStringIndenter().levels(levels).get(s);
}
static public String structForUser(Object o) {
return structureForUser(o);
}
static public String structForUser(Object o, structure_Data data) {
return structureForUser(o, data);
}
static public boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static public int strL(String s) {
return s == null ? 0 : s.length();
}
static public int listL(Collection l) {
return l == null ? 0 : l.size();
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static public void setOpt_raw(Object o, String field, Object value) {
try {
if (o == null)
return;
if (o instanceof Class)
setOpt_raw((Class) o, field, value);
else {
Field f = setOpt_raw_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
smartSet(f, o, value);
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void setOpt_raw(Class c, String field, Object value) {
try {
if (c == null)
return;
Field f = setOpt_raw_findStaticField(c, field);
if (f != null) {
makeAccessible(f);
smartSet(f, null, value);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Field setOpt_raw_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static public Field setOpt_raw_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static public void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
if (type == int.class && value instanceof Long) {
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 public A setDyn(A o, String key, Object value) {
setDynObjectValue(o, key, value);
return o;
}
static public void setDyn(IMeta o, String key, Object value) {
metaMapPut(o, key, value);
}
static public ClassLoader classLoaderForObject(Object o) {
if (o instanceof ClassLoader)
return ((ClassLoader) o);
if (o == null)
return null;
return _getClass(o).getClassLoader();
}
static public String classNameToVM(String name) {
return name.replace(".", "$");
}
static public JavaClass classToBCEL(Class c) {
try {
InputStream in = inputStreamForClass(c);
try {
return in == null ? null : new ClassParser(in, c.getName() + ".class").parse();
} finally {
_close(in);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public JavaClass classToBCEL(Object o) {
return classToBCEL(_getClass(o));
}
static public String tabToSingleSpace(String s) {
return replace(s, '\t', ' ');
}
static public void printWithNLBeforeAndAfter(Object o) {
print_doubleNL(o);
}
static public A printWithIndent(A o) {
return printIndent(o);
}
static public A printWithIndent(String indent, A o) {
return printIndent(indent, o);
}
static public void printWithIndent(int indent, Object o) {
printIndent(indent, o);
}
static public Map synchroHashMap() {
return synchronizedMap(new HashMap());
}
static public boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null)
return false;
if (o instanceof ThreadLocal)
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static public boolean isTrue(Boolean b) {
return b != null && b.booleanValue();
}
static public boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean isEmpty(File f) {
return f == null || f.length() == 0;
}
static public boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean isEmpty(Object[] a) {
return a == null || a.length == 0;
}
static public boolean isEmpty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
static public boolean isEmpty(AppendableChain c) {
return c == null;
}
static public boolean isEmpty(IntSize l) {
return l == null || l.size() == 0;
}
static public Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
static public Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
static public String beautifyStructure(String s) {
List tok = javaTokForStructure(s);
structure_addTokenMarkers(tok);
jreplace(tok, "lhm", "");
return join(tok);
}
static public boolean structure_showTiming, structure_checkTokenCount;
static public String structure(Object o) {
return structure(o, new structure_Data());
}
static public 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 public void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack)) popLast(d.stack).run();
}
static public void structureToPrintWriter(Object o, PrintWriter out) {
structureToPrintWriter(o, out, new structure_Data());
}
static public void structureToPrintWriter(Object o, PrintWriter out, structure_Data d) {
d.out = out;
structure_go(o, d);
}
static public boolean structure_allowShortening = false;
static public class structure_ClassInfo {
public Class c;
public String shortName;
public List fields;
public Method customSerializer;
public IVF1 serializeObject;
public boolean special = false;
public boolean nullInstances = false;
public boolean javafy = false;
public Object emptyInstance;
public String toString() {
return commaCombine("Class " + className(c), stringIf("special", special), stringIf("customSerializer", customSerializer != null), stringIf("javafy", javafy), stringIf("nullInstances", nullInstances));
}
public void nullInstances(boolean b) {
this.nullInstances = b;
if (b)
special = true;
}
public void javafy(boolean b) {
this.javafy = b;
if (b)
special = true;
}
public boolean handle(A o) {
return false;
}
}
static public class structure_Data {
public PrintWriter out;
public int stringSizeLimit;
public int shareStringsLongerThan = 20;
public boolean noStringSharing = false;
public boolean storeBaseClasses = false;
public boolean honorFieldOrder = true;
public 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;
}
public 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;
}
public boolean stackTraceIfUnpersistable = true;
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;
}
public boolean skipDefaultValues = false;
public structure_Data d() {
return this;
}
transient public IF1 shouldIncludeField;
public boolean shouldIncludeField(Field f) {
return shouldIncludeField != null ? shouldIncludeField.get(f) : shouldIncludeField_base(f);
}
final public boolean shouldIncludeField_fallback(IF1 _f, Field f) {
return _f != null ? _f.get(f) : shouldIncludeField_base(f);
}
public boolean shouldIncludeField_base(Field f) {
return true;
}
public IdentityHashMap seen = new IdentityHashMap();
public HashMap strings = new HashMap();
public HashSet concepts = new HashSet();
public HashMap infoByClass = new HashMap();
public HashMap> persistenceInfo = new HashMap();
public int n;
public List stack = new ArrayList();
public structure_Data append(String token) {
out.print(token);
++n;
return this;
}
public structure_Data append(int i) {
out.print(i);
++n;
return this;
}
public structure_Data append(String token, int tokCount) {
out.print(token);
n += tokCount;
return this;
}
public structure_Data app(String token) {
out.print(token);
return this;
}
public structure_Data app(int i) {
out.print(i);
return this;
}
public structure_Data app(char c) {
out.print(c);
return this;
}
public structure_ClassInfo infoForClass(Class c) {
structure_ClassInfo info = infoByClass.get(c);
if (info == null)
info = newClass(c);
return info;
}
transient public IF1 realShortName;
public String realShortName(String name) {
return realShortName != null ? realShortName.get(name) : realShortName_base(name);
}
final public String realShortName_fallback(IF1 _f, String name) {
return _f != null ? _f.get(name) : realShortName_base(name);
}
public String realShortName_base(String name) {
return dropPrefix("main$", dropPrefix("loadableUtils.utils$", dropPrefix(mcDollar, name)));
}
public structure_ClassInfo newClass(Class c) {
var d = d();
boolean isJavaXClass = isJavaXClassName(c.getName(), mcDollar);
if (c == String.class)
return new structure_ClassInfo() {
@Override
public 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
public boolean handle(File o) {
append("File ").append(quote(o.getPath()));
return true;
}
};
if (!isJavaXClass) {
if (isSubClassOf(c, Set.class))
return new structure_ClassInfo() {
@Override
public boolean handle(Set o) {
writeSet(o);
return true;
}
};
if (isSubClassOf(c, Collection.class))
return new structure_ClassInfo() {
@Override
public boolean handle(Collection o) {
writeCollection(o);
return true;
}
};
if (isSubClassOf(c, Map.class))
return new structure_ClassInfo() {
@Override
public 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;
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
public boolean handle(SynchronizedMap o) {
append("sync ");
structure_1(o.m, d);
return true;
}
};
if (isSubClassOf(c, SynchronizedList.class))
return new structure_ClassInfo() {
@Override
public boolean handle(SynchronizedList o) {
append("sync ");
structure_1(unwrapSynchronizedList(o), d);
return true;
}
};
if (c.isArray()) {
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);
}
}
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;
}
public void setFields(structure_ClassInfo info, List fields) {
info.fields = fields;
}
public void writeObject(Object o, String shortName, Map fv) {
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
append(shortName);
n += countDots(shortName) * 2;
int l = n;
Iterator it = fv.entrySet().iterator();
class WritingObject implements Runnable {
public 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());
}
public 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 {
public boolean v = false;
public 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());
}
public void writeSet(Set o) {
var d = this;
String name = o.getClass().getName();
if (o instanceof TreeSet) {
d.append(isCISet_gen(o) ? "ciset" : "treeset");
structure_1(new ArrayList(o), d);
return;
}
d.append(o instanceof LinkedHashSet ? "lhs" : "hashset");
structure_1(new ArrayList(o), d);
}
public void writeCollection(Collection o) {
var d = this;
String name = o.getClass().getName();
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...";
}
});
}
}
static public 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);
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 || o instanceof Rectangle;
if (referencable) {
Integer ref = d.seen.get(o);
if (ref != null) {
d.append("t").app(ref);
return;
}
d.seen.put(o, d.n);
}
if (info.handle(o)) {
return;
}
if (info.special) {
if (info.javafy) {
d.append("j ").append(quote(str(o)));
return;
}
if (c.isEnum()) {
d.append("enum ");
d.append(info.shortName);
d.out.append(' ');
d.append(((Enum) o).ordinal());
return;
}
if (info.customSerializer != null) {
Object o2 = invokeMethod(info.customSerializer, o);
if (o2 == o) {
} 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) {
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) {
{
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";
if (o instanceof int[]) {
atype = "intarray";
} else if (o instanceof double[]) {
atype = "dblarray";
} else if (o instanceof float[]) {
atype = "floatarray";
} else {
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";
if (p.b > 1) {
atype += "/" + p.b;
d.n += 2;
}
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
public int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0)
d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")");
return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")");
return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
if (d.n != l)
d.append(", ");
d.append(i);
}
d.append("}");
return;
}
String dynName = shortDynClassNameForStructure(o);
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
Class cc = c;
while (cc != Object.class) {
for (Field field : getDeclaredFields_cached(cc)) {
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);
}
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);
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;
}
}
d.setFields(info, lFields);
}
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");
LinkedHashMap fv = new LinkedHashMap();
Object defaultInstance = info.emptyInstance;
if (!referencable)
throw fail("Not referencable: " + className(o));
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);
}
String shortName = info.shortName;
Object classNameFromFV = fv.get("className");
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) {
shortName = shortDynClassNameForStructure((DynamicObject) o);
fv.remove("className");
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 public String unnullForIteration(String s) {
return s == null ? "" : s;
}
static public Collection unnullForIteration(Collection l) {
return l == null ? immutableEmptyList() : l;
}
static public List unnullForIteration(List l) {
return l == null ? immutableEmptyList() : l;
}
static public byte[] unnullForIteration(byte[] l) {
return l == null ? emptyByteArray() : l;
}
static public int[] unnullForIteration(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnullForIteration(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnullForIteration(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public short[] unnullForIteration(short[] l) {
return l == null ? emptyShortArray() : l;
}
static public Map unnullForIteration(Map l) {
return l == null ? immutableEmptyMap() : l;
}
static public Iterable unnullForIteration(Iterable i) {
return i == null ? immutableEmptyList() : i;
}
static public A[] unnullForIteration(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnullForIteration(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnullForIteration(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnullForIteration(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnullForIteration(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public long unnullForIteration(Long l) {
return l == null ? 0L : l;
}
static public void addAll(Collection c, Iterable b) {
if (c != null && b != null)
for (A a : b) c.add(a);
}
static public boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static public boolean addAll(Collection c, B... b) {
return c != null && b != null && c.addAll(Arrays.asList(b));
}
static public Map addAll(Map a, Map extends A, ? extends B> b) {
if (a != null && b != null)
a.putAll(b);
return a;
}
static public A addAll(A c, Collection extends Component> components) {
return addComponents(c, components);
}
static public A addAll(A c, Component... components) {
return addComponents(c, components);
}
static public void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null)
map.put(key, value);
}
static public void mapPut(Map map, Pair p) {
if (map != null && p != null)
map.put(p.a, p.b);
}
static public List mapCodeTokens(Object f, List l) {
List out = emptyList(l);
for (int i = 0; i < l(l); i++) {
Object o = l.get(i);
out.add(odd(i) ? callF(f, o) : o);
}
return out;
}
static public List mapCodeTokens(List l, Object f) {
return mapCodeTokens(f, l);
}
static public List mapCodeTokens(List tok, IF1 f) {
return mapCodeTokens(tok, (Object) f);
}
static public List mapCodeTokens(IF1 f, List tok) {
return mapCodeTokens(tok, f);
}
static public Map> javaTok_cached_cache = synchronizedMRUCache(100);
static public List javaTok_cached(String s) {
List tok = javaTok_cached_cache.get(s);
if (tok == null)
javaTok_cached_cache.put(s, tok = javaTok(s));
return tok;
}
static public AutoCloseable tempSetThreadLocalIfNecessary(ThreadLocal tl, A a) {
if (tl == null)
return null;
A prev = tl.get();
if (eq(prev, a))
return null;
tl.set(a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
static public AutoCloseable tempSetThreadLocalIfNecessary(BetterThreadLocal tl, A a) {
if (tl == null)
return null;
A prev = tl.get();
if (eq(prev, a))
return null;
tl.set(a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
static public Class __javax;
static public Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void __setJavaX(Class j) {
__javax = j;
_onJavaXSet();
}
static public Class run(String progID, String... args) {
Class main = hotwire(progID);
callMain(main, args);
return main;
}
static public void restart() {
Object j = getJavaX();
call(j, "cleanRestart", get(j, "fullArgs"));
}
static public PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static public boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x))
return true;
return false;
}
static public boolean startsWithOneOf(String s, Matches m, String... l) {
for (String x : l) if (startsWith(s, x, m))
return true;
return false;
}
static public boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static public String hostNameFromURL(String url) {
try {
return empty(url) ? null : new URL(url).getHost();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object pcallF_minimalExceptionHandling(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable e) {
System.out.println(getStackTrace(e));
_storeException(e);
}
return null;
}
static public Set vm_generalIdentityHashSet(Object name) {
synchronized (vm_generalMap()) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = syncIdentityHashSet());
return set;
}
}
static public Map vm_generalHashMap(Object name) {
synchronized (vm_generalMap()) {
Map m = (Map) (vm_generalMap_get(name));
if (m == null)
vm_generalMap_put(name, m = syncHashMap());
return m;
}
}
static public A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
static public HashMap> callMC_cache = new HashMap();
static public String callMC_key;
static public Method callMC_value;
static public Object callMC(String method, String[] arg) {
return callMC(method, new Object[] { arg });
}
static public Object callMC(String method, Object... args) {
try {
Method me;
if (callMC_cache == null)
callMC_cache = new HashMap();
synchronized (callMC_cache) {
me = method == callMC_key ? callMC_value : null;
}
if (me != null)
try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
List m;
synchronized (callMC_cache) {
m = callMC_cache.get(method);
}
if (m == null) {
if (callMC_cache.isEmpty()) {
callMC_makeCache();
m = callMC_cache.get(method);
}
if (m == null)
throw fail("Method named " + method + " not found in main");
}
int n = m.size();
if (n == 1) {
me = m.get(0);
synchronized (callMC_cache) {
callMC_key = method;
callMC_value = me;
}
try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
}
for (int i = 0; i < n; i++) {
me = m.get(i);
if (call_checkArgs(me, args, false))
return invokeMethod(me, null, args);
}
throw fail("No method called " + method + " with arguments (" + joinWithComma(getClasses(args)) + ") found in main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void callMC_makeCache() {
synchronized (callMC_cache) {
callMC_cache.clear();
Class _c = (Class) mc(), c = _c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
makeAccessible(m);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
static public List synchroList() {
return synchroList(new ArrayList ());
}
static public List synchroList(List l) {
return new SynchronizedList(l);
}
static public Object call(Object o) {
return callF(o);
}
static public Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] { arg });
}
static public Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
static public A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static public A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static public 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 public List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
static public double parseDouble(String s) {
return empty(s) ? 0.0 : Double.parseDouble(s);
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
static public BetterThreadLocal pingSource_tl_var = new BetterThreadLocal