Warning : session_start(): open(/var/lib/php/sessions/sess_q9lf5o6usn5s7eui19pfpf6l0a, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import java.util.function.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.imageio.*;
import java.math.*;
import java.time.Duration;
import java.lang.invoke.VarHandle;
import java.lang.invoke.MethodHandles;
import java.awt.geom.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import static x30_pkg.x30_util.DynamicObject;
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.jar.*;
import java.text.*;
import java.text.NumberFormat;
import java.nio.charset.Charset;
import java.util.TimeZone;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
public class main {
static public void test_leftArrowScript_pcall() {
List errors = new ArrayList();
AutoCloseable __2 = tempSetPCallPolicyForThread(e -> errors.add(e));
try {
assertNullVerbose(leftArrowScript("\r\n pcall { fail \"What\" }\r\n "));
assertEqualsVerbose(1, l(errors));
assertEqualsVerbose("What", first(errors).getMessage());
} finally {
_close(__2);
}
}
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 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 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 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 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 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(MultiSet 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 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 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 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 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 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 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(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 str(first((Collection) strings));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(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 int random(Random r, int n) {
return n <= 0 ? 0 : getRandomizer(r).nextInt(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 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 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 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 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 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 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 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 Object leftArrow(String script) {
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
parser.allowTheWorld();
return parser.parse(script).get();
}
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 String appendColonIfNempty(String s) {
return empty(s) ? "" : s + ": ";
}
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 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 Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
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 AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static public RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
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 List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
static volatile public boolean ping_pauseAll = false;
static public int ping_sleep = 100;
static volatile public boolean ping_anyActions = false;
static public Map ping_actions = newWeakHashMap();
static public ThreadLocal ping_isCleanUpThread = new ThreadLocal();
static public boolean ping(PingSource pingSource) {
return ping();
}
static public boolean ping() {
newPing();
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty())
ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 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 void _handleError(Error e) {
}
static public void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
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 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 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 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 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 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 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 String combinePrintParameters(String s, Object o) {
return (endsWithLetterOrDigit(s) ? s + ": " : s) + o;
}
static public void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
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 Class mc() {
return main.class;
}
static public Set> _entrySet(Map map) {
return map == null ? Collections.EMPTY_SET : map.entrySet();
}
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 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 public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static public void newPing() {
var tl = newPing_actionTL();
Runnable action = tl == null ? null : tl.get();
{
if (action != null)
action.run();
}
}
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 void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static public Thread currentThread() {
return Thread.currentThread();
}
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 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 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 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 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 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 A or(A a, A b) {
return a != null ? a : b;
}
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 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 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 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 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 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 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 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 A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
static public boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
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 List immutableEmptyList() {
return Collections.emptyList();
}
static public byte[] emptyByteArray_a = new byte[0];
static public byte[] emptyByteArray() {
return emptyByteArray_a;
}
static public short[] emptyShortArray = new short[0];
static public short[] emptyShortArray() {
return emptyShortArray;
}
static public Map immutableEmptyMap() {
return Collections.emptyMap();
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
static public List _registerWeakMap_preList;
static public A _registerWeakMap(A map) {
if (javax() == null) {
if (_registerWeakMap_preList == null)
_registerWeakMap_preList = synchroList();
_registerWeakMap_preList.add(map);
return map;
}
try {
call(javax(), "_registerWeakMap", map);
} catch (Throwable e) {
printException(e);
print("Upgrade JavaX!!");
}
return map;
}
static public void _onLoad_registerWeakMap() {
assertNotNull(javax());
if (_registerWeakMap_preList == null)
return;
for (Object o : _registerWeakMap_preList) _registerWeakMap(o);
_registerWeakMap_preList = null;
}
static public x30_pkg.x30_util.BetterThreadLocal newPing_actionTL;
static public x30_pkg.x30_util.BetterThreadLocal newPing_actionTL() {
if (newPing_actionTL == null)
newPing_actionTL = vm_generalMap_getOrCreate("newPing_actionTL", () -> {
Runnable value = (Runnable) (callF_gen(vm_generalMap_get("newPing_valueForNewThread")));
var tl = new x30_pkg.x30_util.BetterThreadLocal();
tl.set(value);
return tl;
});
return newPing_actionTL;
}
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 volatile public boolean licensed_yes = true;
static public boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
static public void licensed_off() {
licensed_yes = false;
}
static public String className(Object o) {
return getClassName(o);
}
static public String[] drop(int n, String[] a) {
n = Math.min(n, a.length);
String[] b = new String[a.length - n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
static public Object[] drop(int n, Object[] a) {
n = Math.min(n, a.length);
Object[] b = new Object[a.length - n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
static public List drop(Iterable c, Object pred) {
return antiFilter(c, pred);
}
static public List drop(Object pred, Iterable c) {
return antiFilter(pred, c);
}
static public List drop(Object pred, Object[] c) {
return antiFilter(pred, c);
}
static public List drop(Iterable c, F1 pred) {
return antiFilter(c, pred);
}
static public List drop(F1 pred, Iterable c) {
return antiFilter(pred, c);
}
static public List drop(Iterable c, IF1 pred) {
return antiFilter(c, pred);
}
static public List drop(IF1 pred, Iterable c) {
return antiFilter(pred, c);
}
static public ArrayList toList(A[] a) {
return asList(a);
}
static public ArrayList toList(int[] a) {
return asList(a);
}
static public ArrayList toList(short[] a) {
return asList(a);
}
static public ArrayList toList(long[] a) {
return asList(a);
}
static public ArrayList toList(Set s) {
return asList(s);
}
static public ArrayList toList(Iterable s) {
return asList(s);
}
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 boolean isDigit(char c) {
return Character.isDigit(c);
}
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 List> _threadInfo_makers = synchroList();
static public Object _threadInfo() {
if (empty(_threadInfo_makers))
return null;
HashMap map = new HashMap();
pcallFAll(_threadInfo_makers, map);
return map;
}
static public Runnable asRunnable(Object o) {
return toRunnable(o);
}
static public void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
static public ThreadLocal customRandomizerForThisThread_tl = new ThreadLocal();
static public ThreadLocal customRandomizerForThisThread_tl() {
return customRandomizerForThisThread_tl;
}
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 Class javax() {
return getJavaX();
}
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 Map synchroHashMap() {
return synchronizedMap(new HashMap());
}
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 HashSet litset(A... items) {
return lithashset(items);
}
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 int iround(double d) {
return (int) Math.round(d);
}
static public int iround(Number n) {
return iround(toDouble(n));
}
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 printException(A e) {
printStackTrace(e);
return e;
}
static public A vm_generalMap_getOrCreate(Object key, F0 create) {
return vm_generalMap_getOrCreate(key, f0ToIF0(create));
}
static public A vm_generalMap_getOrCreate(Object key, IF0 create) {
Map generalMap = vm_generalMap();
if (generalMap == null)
return null;
synchronized (generalMap) {
A a = (A) (vm_generalMap_get(key));
if (a == null)
vm_generalMap_put(key, a = create == null ? null : create.get());
return a;
}
}
static public A callF_gen(F0 f) {
return f == null ? null : f.get();
}
static public B callF_gen(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public A callF_gen(IF0 f) {
return f == null ? null : f.get();
}
static public B callF_gen(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF_gen(A a, IF1 f) {
return f == null ? null : f.get(a);
}
static public C callF_gen(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public void callF_gen(VF1 f, A a) {
{
if (f != null)
f.get(a);
}
}
static public void callF_gen(A a, IVF1 f) {
{
if (f != null)
f.get(a);
}
}
static public void callF_gen(IVF1 f, A a) {
{
if (f != null)
f.get(a);
}
}
static public Object callF_gen(Runnable r) {
{
if (r != null)
r.run();
}
return null;
}
static public Object callF_gen(Object f, Object... args) {
return callF(f, args);
}
static public Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static public List antiFilter(Iterable c, Object pred) {
if (pred instanceof F1)
return antiFilter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null)
for (Object o : c) if (!isTrue(callF(pred, o)))
x.add(o);
return x;
}
static public List antiFilter(Object pred, Iterable c) {
return antiFilter(c, pred);
}
static public List antiFilter(Object pred, Object[] c) {
return antiFilter(pred, wrapArrayAsList(c));
}
static public List antiFilter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (!pred.get(o).booleanValue())
x.add(o);
return x;
}
static public List antiFilter(F1 pred, Iterable c) {
return antiFilter(c, pred);
}
static public List antiFilter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (!pred.get(o).booleanValue())
x.add(o);
return x;
}
static public List antiFilter(IF1 pred, Iterable c) {
return antiFilter(c, pred);
}
static public int strL(String s) {
return s == null ? 0 : s.length();
}
static public int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
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 void pcallFAll(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) pcallF(f, args);
}
static public void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static public Runnable toRunnable(final Object o) {
if (o == null)
return null;
if (o instanceof Runnable)
return (Runnable) o;
if (o instanceof String)
throw fail("callF_legacy");
return new Runnable() {
public void run() {
try {
callF(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(o)";
}
};
}
static public List> _threadInheritInfo_retrievers = synchroList();
static public void _threadInheritInfo(Object info) {
if (info == null)
return;
pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
static public String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(Object... c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static public List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static public void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
static public void multiMapPut(MultiMap mm, A key, B value) {
if (mm != null && key != null && value != null)
mm.put(key, value);
}
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 Object call_withVarargs(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(methodName, args);
if (me != null)
return invokeMethod(me, null, args);
List methods = cache.cache.get(methodName);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
{
if (!(isStaticMethod(m)))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + methodName + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(methodName);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + methodName + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Map synchronizedMap() {
return synchroMap();
}
static public Map synchronizedMap(Map map) {
return synchroMap(map);
}
static public HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
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 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 boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
static public String theAGIBlueDomain() {
return "agi.blue";
}
static public Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static public Throwable _storeException_value;
static public void _storeException(Throwable e) {
_storeException_value = e;
}
static public Map vm_generalMap_map;
static public Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
static public Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static public Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static public Map syncHashMap() {
return synchroHashMap();
}
static public A printStackTrace(A e) {
if (e != null)
print(getStackTrace(e));
return e;
}
static public void printStackTrace() {
printStackTrace(new Throwable());
}
static public void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static public void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static public IF0 f0ToIF0(F0 f) {
return f == null ? null : () -> f.get();
}
static public List wrapArrayAsList(A[] a) {
return a == null ? null : Arrays.asList(a);
}
static public Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static public A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
static public B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
static public void pcallF(VF1 f, A a) {
try {
{
if (f != null)
f.get(a);
}
} catch (Throwable __e) {
printStackTrace(__e);
}
}
static public Object pcallF(Runnable r) {
try {
{
if (r != null)
r.run();
}
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
static public A pcallF(IF0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
static public B pcallF(IF1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
static public void _onJavaXSet() {
}
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 Object[] massageArgsForVarArgsCall(Executable m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = l(args);
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
int nVarArgs = nArgs - n;
Object varArgs = Array.newInstance(varArgType, nVarArgs);
for (int i = 0; i < nVarArgs; i++) Array.set(varArgs, i, args[n + i]);
newArgs[n] = varArgs;
return newArgs;
}
static public double parseDouble(String s) {
return empty(s) ? 0.0 : Double.parseDouble(s);
}
static public boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
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 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 ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static public boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
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 B mapPutOrRemove(Map map, A key, B value) {
if (map != null && key != null)
if (value != null)
return map.put(key, value);
else
return map.remove(key);
return null;
}
static public Set synchronizedSet() {
return synchroHashSet();
}
static public Set synchronizedSet(Set set) {
return new SynchronizedSet(set);
}
static public Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
static public Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
printStackTrace(__e);
}
return null;
}
static public boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static public boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
static public void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, Math.min(a.length, b.length));
}
static public void arraycopy(Object src, int srcPos, int destPos, int n) {
arraycopy(src, srcPos, src, destPos, n);
}
static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
static public String asString(Object o) {
return o == null ? null : o.toString();
}
static public boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
}
static public boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b))
return false;
if (m != null)
m.m = new String[] { substring(a, 0, l(a) - l(b)) };
return true;
}
static public Object getOptDynOnly(DynamicObject o, String field) {
if (o == null || o.fieldValues == null)
return null;
return o.fieldValues.get(field);
}
static public Set synchroHashSet() {
return synchronizedSet(new HashSet ());
}
static public boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static abstract public class VF1 implements IVF1 {
public abstract void get(A a);
}
final static public class _MethodCache {
final public Class c;
final public HashMap> cache = new HashMap();
public _MethodCache(Class c) {
this.c = c;
_init();
}
public void _init() {
Class _c = c;
java.lang.Module myModule = getClass().getModule();
boolean anyHiddenClasses = false;
while (_c != null) {
boolean exported = classIsExportedTo(_c, myModule);
if (!exported)
anyHiddenClasses = true;
else
for (Method m : _c.getDeclaredMethods()) if ((anyHiddenClasses || !isAbstract(m)) && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
_c = _c.getSuperclass();
}
for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if ((anyHiddenClasses || m.isDefault()) && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
}
public Method findMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public Method findStaticMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (isStaticMethod(me) && call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
static public class Matches {
public String[] m;
public Matches() {
}
public Matches(String... m) {
this.m = m;
}
public String get(int i) {
return i < m.length ? m[i] : null;
}
public String unq(int i) {
return unquote(get(i));
}
public String tlc(int i) {
return unq(i).toLowerCase();
}
public boolean bool(int i) {
return "true".equals(unq(i));
}
public String rest() {
return m[m.length - 1];
}
public int psi(int i) {
return Integer.parseInt(unq(i));
}
public String toString() {
return "Matches(" + joinWithComma(quoteAll(asList(m))) + ")";
}
public int hashCode() {
return _hashCode(toList(m));
}
public boolean equals(Object o) {
return o instanceof Matches && arraysEqual(m, ((Matches) o).m);
}
}
static public class Symbol implements CharSequence {
public String text;
public Symbol() {
}
public Symbol(String text, boolean dummy) {
this.text = text;
}
public int hashCode() {
return _hashCode(text);
}
public String toString() {
return text;
}
public boolean equals(Object o) {
return this == o;
}
public int length() {
return text.length();
}
public char charAt(int index) {
return text.charAt(index);
}
public CharSequence subSequence(int start, int end) {
return text.substring(start, end);
}
}
static public class Var implements IVar , ISetter {
public Var() {
}
public Var(A v) {
this.v = v;
}
public A v;
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() {
return v;
}
public synchronized boolean has() {
return v != null;
}
public void clear() {
set(null);
}
public synchronized A getAndSet(A a) {
var value = v;
set(a);
return value;
}
public IF0 getter() {
return () -> get();
}
public IVF1 setter() {
return __35 -> set(__35);
}
public String toString() {
return str(this.get());
}
}
static public class Scorer {
public double score, total;
public List successes, errors;
public boolean verboseFailures, verboseAll;
final public void add(double score) {
addZeroToOne(score);
}
public void addZeroToOne(double score) {
++total;
this.score += clamp(score, 0, 1);
}
public void addZeroToOneError(double error) {
addZeroToOne(1 - error);
}
public void addError() {
add(false);
}
public void addError(A info) {
add(false, info);
}
public void error(A info) {
addError(info);
}
public void addOK() {
add(true);
}
public void addOK(A info) {
add(true, info);
}
public void ok() {
addOK();
}
public void ok(A info) {
addOK(info);
}
public boolean add(boolean correct) {
++total;
if (correct)
++score;
return correct;
}
public boolean add(boolean correct, A info) {
main.add(correct ? successes : errors, info);
if (verboseAll || verboseFailures && !correct)
_print((correct ? "[GOOD] " : "[BAD] ") + info);
return add(correct);
}
public void eq(Object a, Object b) {
if (_eq(a, b))
add(true);
else
add(false, (A) (a + " != " + b));
}
public void print() {
main.print(toString());
}
public String toString() {
return formatDouble(ratioToPercent(score, total), 1) + "% correct (n=" + formatDouble(total, 1) + ")";
}
public double get() {
return ratioToPercent(score, total);
}
public double percentScore() {
return get();
}
public double score() {
return get();
}
public boolean allCorrect() {
return score == total;
}
public void add(Scorer scorer) {
if (scorer == null)
return;
total += scorer.total;
score += scorer.score;
addAll(successes, scorer.successes);
addAll(errors, scorer.errors);
}
public void collectErrors() {
errors = new ArrayList();
}
public void collectSuccesses() {
successes = new ArrayList();
}
}
static public class Timestamp implements Comparable, IFieldsToList {
public long date;
public Timestamp(long date) {
this.date = date;
}
public boolean equals(Object o) {
if (!(o instanceof Timestamp))
return false;
Timestamp __1 = (Timestamp) o;
return date == __1.date;
}
public int hashCode() {
int h = 2059094262;
h = boostHashCombine(h, _hashCode(date));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { date };
}
public Timestamp() {
date = now();
}
public Timestamp(Date date) {
if (date != null)
this.date = date.getTime();
}
public long unixDate() {
return date;
}
public long unixSeconds() {
return unixDate() / 1000;
}
public String toString() {
return formatLocalDateWithSeconds(date);
}
public int compareTo(Timestamp t) {
return t == null ? 1 : cmp(date, t.date);
}
public Timestamp plus(Seconds seconds) {
return plus(seconds == null ? null : seconds.getDouble());
}
final public Timestamp plusSeconds(double seconds) {
return plus(seconds);
}
public Timestamp plus(double seconds) {
return new Timestamp(date + toMS(seconds));
}
public long minus(Timestamp ts) {
return unixDate() - ts.unixDate();
}
public long sysTime() {
return clockTimeToSystemTime(date);
}
public Duration minusAsDuration(Timestamp ts) {
return Duration.ofMillis(minus(ts));
}
}
static public class GazelleV_LeftArrowScriptParser extends SimpleLeftToRightParser {
final public GazelleV_LeftArrowScriptParser setMagicSwitch(boolean magicSwitch) {
return magicSwitch(magicSwitch);
}
public GazelleV_LeftArrowScriptParser magicSwitch(boolean magicSwitch) {
this.magicSwitch = magicSwitch;
return this;
}
final public boolean getMagicSwitch() {
return magicSwitch();
}
public boolean magicSwitch() {
return magicSwitch;
}
public boolean magicSwitch = true;
public ClassNameResolver classNameResolver;
public List functionContainers = new ArrayList();
final public GazelleV_LeftArrowScriptParser setLasClassLoader(ILASClassLoader lasClassLoader) {
return lasClassLoader(lasClassLoader);
}
public GazelleV_LeftArrowScriptParser lasClassLoader(ILASClassLoader lasClassLoader) {
this.lasClassLoader = lasClassLoader;
return this;
}
final public ILASClassLoader getLasClassLoader() {
return lasClassLoader();
}
public ILASClassLoader lasClassLoader() {
return lasClassLoader;
}
public ILASClassLoader lasClassLoader;
final public GazelleV_LeftArrowScriptParser setClassDefPrefix(String classDefPrefix) {
return classDefPrefix(classDefPrefix);
}
public GazelleV_LeftArrowScriptParser classDefPrefix(String classDefPrefix) {
this.classDefPrefix = classDefPrefix;
return this;
}
final public String getClassDefPrefix() {
return classDefPrefix();
}
public String classDefPrefix() {
return classDefPrefix;
}
public String classDefPrefix;
final public GazelleV_LeftArrowScriptParser setOptimize(boolean optimize) {
return optimize(optimize);
}
public GazelleV_LeftArrowScriptParser optimize(boolean optimize) {
this.optimize = optimize;
return this;
}
final public boolean getOptimize() {
return optimize();
}
public boolean optimize() {
return optimize;
}
public boolean optimize = true;
final public GazelleV_LeftArrowScriptParser setUseFixedVarContexts(boolean useFixedVarContexts) {
return useFixedVarContexts(useFixedVarContexts);
}
public GazelleV_LeftArrowScriptParser useFixedVarContexts(boolean useFixedVarContexts) {
this.useFixedVarContexts = useFixedVarContexts;
return this;
}
final public boolean getUseFixedVarContexts() {
return useFixedVarContexts();
}
public boolean useFixedVarContexts() {
return useFixedVarContexts;
}
public boolean useFixedVarContexts = false;
public LASScope scope;
public LinkedHashMap knownVars = new LinkedHashMap();
public List varAccessesToFix = new ArrayList();
public Set closerTokens = litset(";", "}", ")");
public BuildingScript currentReturnableScript;
public BuildingScript currentLoop;
public boolean inParens = false;
public int idCounter;
public Map classDefs = new HashMap();
final public Map getFunctionDefs() {
return functionDefs();
}
public Map functionDefs() {
return functionDefs;
}
public Map functionDefs = new HashMap();
transient public Set>> onKnownVarsSnapshot;
public GazelleV_LeftArrowScriptParser onKnownVarsSnapshot(IVF1> f) {
onKnownVarsSnapshot = createOrAddToSyncLinkedHashSet(onKnownVarsSnapshot, f);
return this;
}
public GazelleV_LeftArrowScriptParser removeKnownVarsSnapshotListener(IVF1> f) {
main.remove(onKnownVarsSnapshot, f);
return this;
}
public void knownVarsSnapshot(Map knownVars) {
if (onKnownVarsSnapshot != null)
for (var listener : onKnownVarsSnapshot) pcallF_typed(listener, knownVars);
}
transient public Set> onTypeHook;
public GazelleV_LeftArrowScriptParser onTypeHook(IVF1 f) {
onTypeHook = createOrAddToSyncLinkedHashSet(onTypeHook, f);
return this;
}
public GazelleV_LeftArrowScriptParser removeTypeHookListener(IVF1 f) {
main.remove(onTypeHook, f);
return this;
}
public void typeHook(LASValueDescriptor type) {
if (onTypeHook != null)
for (var listener : onTypeHook) pcallF_typed(listener, type);
}
static public class EvaluableWrapper implements IFieldsToList {
public GazelleV_LeftArrowScript.Evaluable expr;
public EvaluableWrapper() {
}
public EvaluableWrapper(GazelleV_LeftArrowScript.Evaluable expr) {
this.expr = expr;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + expr + ")";
}
public boolean equals(Object o) {
if (!(o instanceof EvaluableWrapper))
return false;
EvaluableWrapper __17 = (EvaluableWrapper) o;
return eq(expr, __17.expr);
}
public int hashCode() {
int h = 700525824;
h = boostHashCombine(h, _hashCode(expr));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { expr };
}
}
public class BuildingScript {
public int id = ++idCounter;
final public BuildingScript setReturnable(boolean returnable) {
return returnable(returnable);
}
public BuildingScript returnable(boolean returnable) {
this.returnable = returnable;
return this;
}
final public boolean getReturnable() {
return returnable();
}
public boolean returnable() {
return returnable;
}
public boolean returnable = false;
final public BuildingScript setIsLoopBody(boolean isLoopBody) {
return isLoopBody(isLoopBody);
}
public BuildingScript isLoopBody(boolean isLoopBody) {
this.isLoopBody = isLoopBody;
return this;
}
final public boolean getIsLoopBody() {
return isLoopBody();
}
public boolean isLoopBody() {
return isLoopBody;
}
public boolean isLoopBody = false;
public BuildingScript returnableParent, loopParent;
final public BuildingScript setScope(LASScope scope) {
return scope(scope);
}
public BuildingScript scope(LASScope scope) {
this.scope = scope;
return this;
}
final public LASScope getScope() {
return scope();
}
public LASScope scope() {
return scope;
}
public LASScope scope;
public GazelleV_LeftArrowScript.Script script = new GazelleV_LeftArrowScript.Script();
public List steps = new ArrayList();
public Map functionDefs = new HashMap();
public BuildingScript(boolean returnable) {
this();
this.returnable = returnable;
}
public BuildingScript(boolean returnable, boolean isLoopBody) {
this();
this.isLoopBody = isLoopBody;
this.returnable = returnable;
}
public BuildingScript() {
scope = currentScope();
}
public void add(GazelleV_LeftArrowScript.Evaluable step) {
if (step != null)
steps.add(step);
}
public GazelleV_LeftArrowScript.Evaluable get() {
script.scope = scope;
var lastStep = last(steps);
if (lastStep instanceof GazelleV_LeftArrowScript.ReturnFromScript)
if (((GazelleV_LeftArrowScript.ReturnFromScript) lastStep).script == script)
replaceLast(steps, ((GazelleV_LeftArrowScript.ReturnFromScript) lastStep).value);
if (!returnable && l(steps) == 1 && empty(functionDefs))
return first(steps);
if (nempty(functionDefs))
script.functionDefs = functionDefs;
script.steps = toTypedArray(GazelleV_LeftArrowScript.Evaluable.class, steps);
return script;
}
public String toStringLong() {
return pnlToLines(steps);
}
public String toString() {
return formatRecordVars("BuildingScript", "id", id, "returnable", returnable, "returnableParent", returnableParent, "script", script);
}
}
public GazelleV_LeftArrowScript.Script parse(String text) {
setText(text);
init();
return parse();
}
public GazelleV_LeftArrowScript.Script parse() {
GazelleV_LeftArrowScript.Script script = parseReturnableScript();
for (var varAccess : varAccessesToFix) varAccess.resolve();
if (optimize)
script = script.optimizeScript();
return script;
}
public GazelleV_LeftArrowScript.Script parseReturnableScript() {
return (GazelleV_LeftArrowScript.Script) parseScript(new BuildingScript().returnable(true));
}
public GazelleV_LeftArrowScript.Evaluable parseScript(BuildingScript script) {
return linkToSrc(() -> {
script.returnableParent = currentReturnableScript;
script.loopParent = currentLoop;
if (script.returnable)
currentReturnableScript = script;
if (script.isLoopBody)
currentLoop = script;
return parseBuildingScript(script);
});
}
public GazelleV_LeftArrowScript.Evaluable parseBuildingScript(BuildingScript script) {
try {
parseScript_2(script);
var builtScript = script.get();
currentReturnableScript = script.returnableParent;
currentLoop = script.loopParent;
return builtScript;
} catch (Throwable e) {
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("Parsed so far:\n" + script);
throw rethrowAndAppendToMessage(e, squareBracketed(str(lineAndColumn(-1))));
}
}
public void parseScript_2(BuildingScript script) {
AutoCloseable __8 = tempRestoreMap(knownVars);
try {
AssureAdvance assure = new AssureAdvance();
while (assure.get()) {
knownVarsSnapshot(knownVars);
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("parseScript_2: Next token is " + quote(token()));
if (is(";")) {
next();
continue;
}
if (isOneOf("}", ")"))
break;
GazelleV_LeftArrowScript.Evaluable instruction = linkToSrc(() -> parseInstruction(script));
if (instruction != null)
script.add(instruction);
}
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("parseScript_2 done");
knownVarsSnapshot(knownVars);
} finally {
_close(__8);
}
}
public GazelleV_LeftArrowScript.Evaluable parseInstruction(BuildingScript script) {
if (is("param")) {
consume();
String var = assertIdentifier(tpp());
LASValueDescriptor valueDescriptor = new LASValueDescriptor();
if (is(":")) {
var type = parseColonType();
valueDescriptor = LASValueDescriptor.nonExactCanBeNull(type);
}
knownVars.put(var, valueDescriptor);
script.script.params = putOrCreateLinkedHashMap(script.script.params, var, valueDescriptor);
return null;
}
if (is("throw")) {
consume();
return new GazelleV_LeftArrowScript.Throw(parseExpr());
}
if (is("try")) {
consume();
GazelleV_LeftArrowScript.Evaluable body = parseCurlyBlock(new BuildingScript());
while (consumeOpt("catch")) {
String var = consumeIdentifier();
AutoCloseable __9 = tempAddKnownVars(var);
try {
GazelleV_LeftArrowScript.Evaluable catchBlock = parseCurlyBlock(new BuildingScript());
body = new GazelleV_LeftArrowScript.TryCatch(body, var, catchBlock);
} finally {
_close(__9);
}
}
if (consumeOpt("finally")) {
GazelleV_LeftArrowScript.Evaluable finallyBlock = parseCurlyBlock(new BuildingScript());
return new GazelleV_LeftArrowScript.TryFinally(body, finallyBlock);
}
return body;
}
if (isOneOf("return", "ret")) {
consume();
GazelleV_LeftArrowScript.Evaluable expr;
if (atCmdEnd())
expr = _const(null);
else
expr = parseAssignmentOrExpr();
return new GazelleV_LeftArrowScript.ReturnFromScript(currentReturnableScript.script, expr);
}
if (is("continue")) {
consume();
assertCmdEnd();
if (currentLoop == null)
throw fail("continue outside of loop");
return new GazelleV_LeftArrowScript.Continue(currentLoop.script);
}
if (is("temp")) {
consume();
GazelleV_LeftArrowScript.Evaluable tempExpr = parseAssignmentOrExpr();
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("tempExpr", tempExpr);
GazelleV_LeftArrowScript.Evaluable body = parseScript(new BuildingScript());
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("body", body);
return new GazelleV_LeftArrowScript.TempBlock(tempExpr, body);
}
if (is("will") && is(1, "return")) {
consume(2);
GazelleV_LeftArrowScript.Evaluable exp = parseAssignmentOrExpr();
GazelleV_LeftArrowScript.Evaluable body = parseScript(new BuildingScript());
return new GazelleV_LeftArrowScript.WillReturn(exp, body);
}
if (is("class"))
return new GazelleV_LeftArrowScript.ClassDef(new ResolvableLASClass(lasClassLoader, parseClassDef()));
return parseAssignmentOrExpr();
}
public GazelleV_LeftArrowScript.Evaluable parseAssignmentOrExpr() {
{
var __3 = parseAssignmentOpt();
if (__3 != null)
return __3;
}
return parseExpr();
}
public GazelleV_LeftArrowScript.Evaluable parseAssignmentOpt() {
String t = token();
if (isIdentifier(t)) {
Type type = null;
var ptr = ptr();
if (is(1, ":")) {
next();
type = parseColonType();
unconsume();
}
if (is(1, "<") && is(2, "-")) {
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("Found assignment");
next(3);
GazelleV_LeftArrowScript.Evaluable rhs = parseExpr();
assertNotNull("Expression expected", rhs);
boolean newVar = !knownVars.containsKey(t);
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
printVars("newVar", newVar, "t", t, "knownVars", knownVars);
knownVars.put(t, type == null ? new LASValueDescriptor() : LASValueDescriptor.nonExactCanBeNull(type));
return newVar ? new GazelleV_LeftArrowScript.VarDeclaration(t, null, rhs) : new GazelleV_LeftArrowScript.Assignment(t, rhs);
}
ptr(ptr);
}
return null;
}
public GazelleV_LeftArrowScript.Evaluable parseOptionalInnerExpression() {
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
printVars("parseOptionalInnerExpression", "token", token());
if (atCmdEnd() || isOneOf("{", ",", "then"))
return null;
return parseInnerExpr();
}
public GazelleV_LeftArrowScript.Evaluable _const(Object o) {
return new GazelleV_LeftArrowScript.Const(o);
}
public GazelleV_LeftArrowScript.Evaluable parseInnerExpr() {
return parseExpr(true);
}
public GazelleV_LeftArrowScript.Evaluable parseExpr() {
if (metaGet("scaffolding") != null)
scaffoldCalled(this, "parseExpr");
return parseExpr(false);
}
public GazelleV_LeftArrowScript.Evaluable parseExpr(boolean inner) {
GazelleV_LeftArrowScript.Evaluable e = linkToSrc(() -> inner ? parseExpr_impl(true) : parseFullExpr());
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("parseExpr done:\n" + GazelleV_LeftArrowScript.indentedScriptStruct(e));
return e;
}
public GazelleV_LeftArrowScript.Evaluable parseFullExpr() {
return parseExprPlusOptionalComma();
}
public GazelleV_LeftArrowScript.CallOnTarget parseThenCall(GazelleV_LeftArrowScript.CallOnTarget expr) {
consume("then");
GazelleV_LeftArrowScript.CallOnTarget secondCall = (GazelleV_LeftArrowScript.CallOnTarget) (parseCall(null));
return new GazelleV_LeftArrowScript.Then(expr, secondCall);
}
public GazelleV_LeftArrowScript.Evaluable parseExprPlusOptionalComma() {
GazelleV_LeftArrowScript.Evaluable expr = parseExpr_impl(false);
while (consumeOpt(",")) {
expr = parseCall_noCmdEndCheck(expr);
}
return expr;
}
public GazelleV_LeftArrowScript.Evaluable parseExpr_impl(boolean inner) {
if (atEnd())
return null;
String t = token();
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
printVars("parseExpr", "token", t);
if (is(";"))
return null;
if (is("def")) {
var fd = parseFunctionDefinition(currentReturnableScript.functionDefs);
return new GazelleV_LeftArrowScript.Const(fd);
}
if (is("{"))
return parseCurlyBlock(new BuildingScript());
if (is("-") && empty(nextSpace()) && startsWithDigit(token(1)) || startsWithDigit(t)) {
var e = parseNumberLiteral();
return parseCall(inner, e);
}
if (isQuoted(t)) {
var e = parseStringLiteral();
return parseCall(inner, e);
}
if (startsWith(t, '\'')) {
consume();
var e = _const(first(unquote(t)));
return parseCall(inner, e);
}
if (isIdentifier(t)) {
if (is("while"))
return parseWhileLoop();
if (is("for"))
return parseForEach();
if (is("if"))
return parseIfStatement();
if (is("repeat"))
return parseRepeatStatement();
if (is("outer")) {
consume();
var a = parseAssignmentOpt();
if (!(a instanceof GazelleV_LeftArrowScript.Assignment))
throw fail("Assignment expected");
return new GazelleV_LeftArrowScript.AssignmentToOuterVar(((GazelleV_LeftArrowScript.Assignment) a).var, ((GazelleV_LeftArrowScript.Assignment) a).expression);
}
consume();
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("Consumed identifier " + t + ", next token: " + token() + ", inner: " + inner);
var e = parseExprStartingWithIdentifier(t, inner);
return inner ? parseCall(inner, e) : e;
}
if (eq(t, "(")) {
consume();
GazelleV_LeftArrowScript.Evaluable e = parseExpr_inParens();
consume(")");
return parseCall(inner, e);
}
if (isOneOf("&", "|") && empty(nextSpace()) && is(1, token())) {
return parseBinaryOperator();
}
throw fail("Identifier, literal, operator or opening parentheses expected (got: " + quote(t));
}
public GazelleV_LeftArrowScript.Evaluable parseExpr_inParens() {
boolean inParensOld = inParens;
inParens = true;
try {
return parseExpr();
} finally {
inParens = inParensOld;
}
}
public GazelleV_LeftArrowScript.Evaluable parseNumberLiteral() {
String t = consumeMultiTokenLiteral();
if (swic(t, "0x"))
return _const(parseHexInt(dropFirst(t, 2)));
if (swic(t, "0b"))
return _const(intFromBinary(dropFirst(t, 2)));
if (isInteger(t))
return _const(parseIntOrLong(t));
if (ewic(t, "f"))
return _const(parseFloat(t));
if (endsWith(t, "L"))
return _const(parseLong(t));
return _const(parseDouble(t));
}
public GazelleV_LeftArrowScript.Evaluable parseBinaryOperator() {
boolean and = is("&");
next(2);
GazelleV_LeftArrowScript.Evaluable a = parseInnerExpr();
GazelleV_LeftArrowScript.Evaluable b = parseInnerExpr();
return and ? new GazelleV_LeftArrowScript.BoolAnd(a, b) : new GazelleV_LeftArrowScript.BoolOr(a, b);
}
public boolean qualifiedNameContinues() {
return empty(prevSpace()) && eq(token(), ".") && empty(nextSpace()) && isIdentifier(token(1));
}
public GazelleV_LeftArrowScript.Evaluable parseNewExpr() {
String className = assertIdentifier(tpp());
parseTypeArguments(null);
LASClassDef cd = classDefs.get(className);
if (cd != null)
return new GazelleV_LeftArrowScript.NewObject_LASClass(new ResolvableLASClass(lasClassLoader, cd));
var type = knownVars.get(className);
if (type != null)
return new GazelleV_LeftArrowScript.NewObject_UnknownClass(new GazelleV_LeftArrowScript.GetVar(className), parseArguments());
Object o = findExternalObject(className);
if (o instanceof Class) {
Class c = (Class) o;
if (c == List.class)
c = ArrayList.class;
else if (c == Map.class)
c = HashMap.class;
else if (c == Set.class)
c = HashSet.class;
return new GazelleV_LeftArrowScript.NewObject(c, parseArguments());
}
throw new ClassNotFound(className);
}
public GazelleV_LeftArrowScript.Evaluable parseExprStartingWithIdentifier(String t, boolean inner) {
if (eq(t, "true"))
return _const(true);
if (eq(t, "false"))
return _const(false);
if (eq(t, "null"))
return _const(null);
if (eq(t, "new"))
return parseNewExpr();
if (eq(t, "list") && is("{")) {
GazelleV_LeftArrowScript.Script block = parseReturnableCurlyBlock();
GazelleV_LeftArrowScript.Evaluable e = new GazelleV_LeftArrowScript.ListFromScript(block);
return parseCall(inner, e);
}
if (scope != null && scope.useFixedVars) {
var type = scope.declaredVars.get(t);
if (type != null) {
var e = new GazelleV_LeftArrowScript.GetFixedVar(scope, t);
e.scope(scope);
e.returnType(type);
varAccessesToFix.add(e);
return parseCall(inner, e);
}
}
var type = knownVars.get(t);
if (type != null) {
var e = new GazelleV_LeftArrowScript.GetVar(t).returnType(type);
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("Found var acccess: " + e + ", " + (!inner ? "Checking for call" : "Returning expression"));
typeHook(type);
return parseCall(inner, e);
}
if (!inner) {
var fdef = lookupFunction(t);
if (fdef != null)
return new GazelleV_LeftArrowScript.CallFunction(fdef, parseArguments());
}
if (eq(t, "_context"))
return new GazelleV_LeftArrowScript.GetVarContext();
Object o = findExternalObject(t);
if (o == null) {
throw new UnknownObject(t);
} else if (o instanceof EvaluableWrapper) {
return parseCall(inner, ((EvaluableWrapper) o).expr);
} else if (inner)
return _const(o);
else if (o instanceof Class) {
return parseExprStartingWithClass((Class) o);
} else if (o instanceof MethodOnObject) {
if (inner)
throw fail("Can't call methods in arguments");
return new GazelleV_LeftArrowScript.CallMethod(_const(((MethodOnObject) o).object), ((MethodOnObject) o).method, parseArguments());
} else
return parseCall(_const(o));
}
public GazelleV_LeftArrowScript.Evaluable parseExprStartingWithClass(Class c) {
if (atCmdEnd())
return _const(c);
if (is("("))
return new GazelleV_LeftArrowScript.NewObject(c, parseArguments());
{
var __4 = parseLambdaOpt(c);
if (__4 != null)
return __4;
}
if (isIdentifier()) {
String name = tpp();
if (hasStaticMethodNamed(c, name))
return new GazelleV_LeftArrowScript.CallMethod(_const(c), name, parseArguments());
if (isInterface(c))
return parseLambdaMethodRef(c, name);
var field = getField(c, name);
if (field != null) {
assertCmdEnd();
if (!isStaticField(field))
throw fail(field + " is not a static field");
return new GazelleV_LeftArrowScript.GetStaticField(field);
}
throw fail(name + " not found in " + c + " (looked for method or field)");
} else
throw fail("Method name expected: " + token());
}
public GazelleV_LeftArrowScript.Evaluable parseLambdaOpt(Class c) {
if (!isInterface(c))
return null;
var ptr = ptr();
var parameterized = parseTypeArgumentsOpt(c);
if (is("{"))
return finishLambdaDef(c, null);
if (consumeOpt("_")) {
String methodName = consumeIdentifier();
return new GazelleV_LeftArrowScript.LambdaMethodOnArgument(c, methodName, parseArguments());
}
int nArgs = 0;
while (isIdentifier(token(nArgs))) nArgs++;
if (!(is(nArgs, "-") && is(nArgs + 1, ">"))) {
ptr(ptr);
return null;
}
String[] argNames = consumeArray(nArgs);
skip(2);
return finishLambdaDef(c, argNames);
}
public GazelleV_LeftArrowScript.Evaluable finishLambdaDef(Class c, String[] argNames) {
AutoCloseable __10 = tempAddKnownVars(argNames);
try {
GazelleV_LeftArrowScript.Evaluable body;
if (is("{"))
body = parseReturnableCurlyBlock();
else
body = parseExpr();
var lambda = new GazelleV_LeftArrowScript.LambdaDef(c, argNames, body);
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("finishLambdaDef done:\n" + GazelleV_LeftArrowScript.indentedScriptStruct(lambda));
return lambda;
} finally {
_close(__10);
}
}
public GazelleV_LeftArrowScript.Evaluable parseLambdaMethodRef(Class c, String name) {
var fdef = lookupFunction(name);
if (fdef != null) {
GazelleV_LeftArrowScript.Evaluable[] curriedArguments = parseArguments();
return new GazelleV_LeftArrowScript.CurriedScriptFunctionLambda(c, fdef, curriedArguments);
}
Object function = findExternalObject(name);
if (function == null)
throw new UnknownObject(name);
if (function instanceof MethodOnObject) {
Object target = ((MethodOnObject) function).object;
String targetMethod = ((MethodOnObject) function).method;
GazelleV_LeftArrowScript.Evaluable[] curriedArguments = parseArguments();
return new GazelleV_LeftArrowScript.CurriedMethodLambda(c, target, targetMethod, curriedArguments);
} else if (function instanceof Class) {
Class c2 = (Class) function;
assertCmdEnd();
var ctors = constructorsWithNumberOfArguments(c2, 1);
if (empty(ctors))
throw fail("No single argument constructor found in " + c2);
return new GazelleV_LeftArrowScript.CurriedConstructorLambda(c, toArray(Constructor.class, ctors), null);
} else
throw fail(function + " is not an instantiable class or callable method");
}
public GazelleV_LeftArrowScript.FunctionDef lookupFunction(String name) {
var script = currentReturnableScript;
while (script != null) {
var f = script.functionDefs.get(name);
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
printVars("lookupFunction", "script", script, "name", name, "f", f);
if (f != null)
return f;
script = script.returnableParent;
}
return functionDefs.get(name);
}
public GazelleV_LeftArrowScript.Evaluable[] parseArguments() {
List l = new ArrayList();
try {
while (true) {
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("parseArgumentsAsList: token is " + quote(t()));
if (is("+") && empty(nextSpace()) && isIdentifier(token(1))) {
consume();
l.add(_const(token()));
continue;
}
if (consumeOpt("<")) {
GazelleV_LeftArrowScript.Evaluable a = parseFullExpr();
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("parseArgumentsAsList: token after expr is " + quote(t()));
if (a == null)
throw fail("expression expected");
l.add(a);
break;
}
GazelleV_LeftArrowScript.Evaluable a = parseOptionalInnerExpression();
if (a == null)
break;
l.add(a);
}
return toArrayOrNull(GazelleV_LeftArrowScript.Evaluable.class, l);
} catch (Throwable _e) {
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("Arguments parsed so far: " + l);
throw rethrow(_e);
}
}
public String consumeMultiTokenLiteral() {
return consumeUntilSpaceOr(() -> atCmdEnd() || is(","));
}
public boolean atCmdEnd() {
return !inParens && atEndOrLineBreak() || closerTokens.contains(token());
}
public void assertCmdEnd() {
if (!atCmdEnd())
throw fail("Expected end of command, token is: " + quote(token()));
}
public GazelleV_LeftArrowScript.Evaluable parseCall(GazelleV_LeftArrowScript.Evaluable target) {
return parseCall(false, target);
}
public GazelleV_LeftArrowScript.Evaluable parseCall(boolean inner, GazelleV_LeftArrowScript.Evaluable target) {
if (atCmdEnd())
return target;
if (inner) {
{
var __5 = parseTildeCall(target);
if (__5 != null)
return __5;
}
return target;
}
return parseCall_noCmdEndCheck(target);
}
public GazelleV_LeftArrowScript.Evaluable parseCall_noCmdEndCheck(GazelleV_LeftArrowScript.Evaluable target) {
var start = ptr();
if (isIdentifier()) {
String name = tpp();
if (eq(token(), "<") && eq(token(1), "-")) {
next(2);
GazelleV_LeftArrowScript.Evaluable rhs = parseExpr();
return new GazelleV_LeftArrowScript.SetField(target, name, rhs);
}
boolean allowNullReference = consumeOpt("?");
var args = parseArguments();
var call = finalizeCall(start, target, name, args);
set(call, "allowNullReference", allowNullReference);
return call;
}
{
var __6 = parseTildeCall(target);
if (__6 != null)
return __6;
}
return target;
}
public GazelleV_LeftArrowScript.Evaluable parseTildeCall(GazelleV_LeftArrowScript.Evaluable target) {
var start = ptr();
if (consumeOpt("~")) {
if (isIdentifier()) {
String key = consumeIdentifier();
return parseCall(finalizeCall(start, target, "getOpt", _const(key)));
} else {
int idx = consumeInteger();
return parseCall(finalizeCall(start, target, "listGet", _const(idx)));
}
}
return null;
}
public GazelleV_LeftArrowScript.Evaluable finalizeCall(ListAndIndex start, GazelleV_LeftArrowScript.Evaluable target, String name, GazelleV_LeftArrowScript.Evaluable... args) {
return finalizeCall2(finalizeCall1(start, target, name, args));
}
public GazelleV_LeftArrowScript.Evaluable finalizeCall2(GazelleV_LeftArrowScript.CallOnTarget call) {
while (is("then")) call = parseThenCall(call);
return call;
}
public GazelleV_LeftArrowScript.CallOnTarget finalizeCall1(ListAndIndex start, GazelleV_LeftArrowScript.Evaluable target, String name, GazelleV_LeftArrowScript.Evaluable... args) {
if (magicSwitch) {
Object ext = findExternalObject(name);
if (ext instanceof MethodOnObject) {
if (nempty(args))
return new GazelleV_LeftArrowScript.CallMethodOrGlobalFunction(target, name, ((MethodOnObject) ext), args);
else
return new GazelleV_LeftArrowScript.CallMethodOrGetFieldOrGlobalFunction(target, name, ((MethodOnObject) ext));
}
}
if (nempty(args))
return new GazelleV_LeftArrowScript.CallMethod(target, name, args);
else
return linkToSrc(start, new GazelleV_LeftArrowScript.CallMethodOrGetField(target, name));
}
public A linkToSrc(ListAndIndex start, A a) {
if (a instanceof IHasTokenRangeWithSrc)
((IHasTokenRangeWithSrc) a).setTokenRangeWithSrc(new TokenRangeWithSrc(start, ptr().plus(-1)));
return a;
}
public A linkToSrc(IF0 a) {
var start = ptr();
return linkToSrc(start, a.get());
}
transient public IF1 findExternalObject;
public Object findExternalObject(String name) {
return findExternalObject != null ? findExternalObject.get(name) : findExternalObject_base(name);
}
final public Object findExternalObject_fallback(IF1 _f, String name) {
return _f != null ? _f.get(name) : findExternalObject_base(name);
}
public Object findExternalObject_base(String name) {
{
var __7 = parsePrimitiveType(name);
if (__7 != null)
return __7;
}
if (qualifiedNameContinues()) {
int idx = idx() - 2;
do next(2); while (qualifiedNameContinues());
String fqn = joinSubList(tok, idx, idx() - 1);
return classForName(fqn);
}
String fullName = globalClassNames().get(name);
if (fullName != null)
return classForName(fullName);
for (var container : unnullForIteration(functionContainers)) {
if (hasMethodNamed(container, name)) {
var moo = new MethodOnObject(container, name);
return moo;
}
var field = getField(container, name);
if (field != null && isStaticField(field))
return new EvaluableWrapper(new GazelleV_LeftArrowScript.GetStaticField(field));
}
return null;
}
public GazelleV_LeftArrowScriptParser allowTheWorld() {
return allowTheWorld(mc());
}
public GazelleV_LeftArrowScriptParser allowTheWorld(Object... functionContainers) {
for (Object o : unnullForIteration(reversed(functionContainers))) if (!contains(this.functionContainers, o)) {
this.functionContainers.add(0, o);
globalClassNames_cache = null;
}
return this;
}
public void printFunctionDefs(GazelleV_LeftArrowScript.Script script) {
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print(values(script.functionDefs));
}
public AutoCloseable tempAddKnownVars(String... vars) {
return tempAddKnownVars(asList(vars));
}
public AutoCloseable tempAddKnownVars(Iterable vars) {
var newVars = mapWithSingleValue(vars, new LASValueDescriptor());
return tempAddKnownVars(newVars);
}
public AutoCloseable tempAddKnownVars(Map newVars) {
if (scope != null)
for (var __1 : _entrySet(newVars)) {
var name = __1.getKey();
var type = __1.getValue();
scope.addDeclaredVar(name, type);
}
return tempMapPutAll(knownVars, newVars);
}
public String parseFunctionDefArg(Map argsOut) {
if (consumeOpt("(")) {
String result = parseFunctionDefArg(argsOut);
consume(")");
return result;
}
if (isIdentifier()) {
String arg = tpp();
var type = typeToValueDescriptor(parseColonTypeOpt());
argsOut.put(arg, type);
return arg;
}
return null;
}
public GazelleV_LeftArrowScript.FunctionDef parseFunctionDefinition(Map functionDefsToAddTo) {
consume("def");
String functionName = assertIdentifier(tpp());
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("parseFunctionDefinition " + functionName);
LinkedHashMap args = new LinkedHashMap();
while (parseFunctionDefArg(args) != null) {
}
var returnType = parseColonTypeOpt();
var fd = new GazelleV_LeftArrowScript.FunctionDef(functionName, keysList(args), null);
{
if (functionDefsToAddTo != null)
functionDefsToAddTo.put(functionName, fd);
}
var scope = newScope();
scope.useFixedVars(useFixedVarContexts);
AutoCloseable __11 = tempScope(scope);
try {
AutoCloseable __12 = tempAddKnownVars(args);
try {
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("Parsing function body");
fd.body = parseReturnableCurlyBlock();
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("Defined function " + functionName + ", added to " + functionDefsToAddTo);
fd.scope(scope);
if (returnType != null)
fd.returnType(returnType);
return fd;
} finally {
_close(__12);
}
} finally {
_close(__11);
}
}
public LASScope newScope() {
return new LASScope(scope);
}
public LASScope currentScope() {
return scope;
}
public AutoCloseable tempScope(LASScope scope) {
var oldScope = currentScope();
this.scope = scope;
return () -> {
scope.resolve();
this.scope = oldScope;
};
}
public GazelleV_LeftArrowScript.Script parseReturnableCurlyBlock() {
return (GazelleV_LeftArrowScript.Script) parseCurlyBlock(new BuildingScript().returnable(true));
}
public GazelleV_LeftArrowScript.Evaluable parseCurlyBlock(BuildingScript script) {
consume("{");
boolean inParensOld = inParens;
inParens = false;
var body = parseScript(script);
consume("}");
inParens = inParensOld;
return body;
}
public GazelleV_LeftArrowScript.Evaluable parseWhileLoop() {
consume("while");
var condition = parseExpr();
var body = parseCurlyBlock(new BuildingScript().isLoopBody(true));
return new GazelleV_LeftArrowScript.While(condition, body);
}
public GazelleV_LeftArrowScript.Evaluable parseForEach() {
return new ParseForEach().get();
}
public class ParseForEach {
public GazelleV_LeftArrowScript.Evaluable collection, body;
public IF0 finish;
public Set vars = new HashSet();
public String addVar(String var) {
return addAndReturn(vars, var);
}
public String consumeVar() {
return addVar(consumeIdentifier());
}
public void parseBody() {
AutoCloseable __13 = tempAddKnownVars(vars);
try {
body = parseCurlyBlock(new BuildingScript().isLoopBody(true));
} finally {
_close(__13);
}
}
public GazelleV_LeftArrowScript.Evaluable get() {
consume("for");
if (is(1, "to")) {
String var = consumeVar();
consume("to");
GazelleV_LeftArrowScript.Evaluable endValue = parseExpr();
parseBody();
return new GazelleV_LeftArrowScript.ForIntTo(endValue, var, body);
}
int iIn = relativeIndexOf("in");
if (iIn < 0)
throw fail("for without in");
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("iIn", iIn);
if (iIn == 1) {
String var = consumeVar();
finish = () -> new GazelleV_LeftArrowScript.ForEach(collection, var, body);
} else if (iIn == 2) {
if (consumeOpt("iterator")) {
String var = consumeVar();
finish = () -> new GazelleV_LeftArrowScript.ForIterator(collection, var, body);
} else if (consumeOpt("nested")) {
String var = consumeVar();
finish = () -> new GazelleV_LeftArrowScript.ForNested(collection, var, body);
} else
throw fail("Unknown pattern for 'for' loop");
} else if (iIn == 3) {
if (isOneOf("pair", "Pair")) {
consume();
String varA = consumeVar();
String varB = consumeVar();
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
printVars("varA", varA, "varB", varB);
finish = () -> new GazelleV_LeftArrowScript.ForPairs(collection, body, varA, varB);
} else {
String varA = consumeVar();
consume(",");
String varB = consumeVar();
finish = () -> new GazelleV_LeftArrowScript.ForKeyValue(collection, body, varA, varB);
}
} else if (iIn == 4) {
consume("index");
String varIndex = consumeVar();
consume(",");
String varElement = consumeVar();
finish = () -> new GazelleV_LeftArrowScript.ForIndex(collection, body, varIndex, varElement);
} else
throw fail("Unknown pattern for 'for' loop");
consume("in");
collection = parseExpr_inParens();
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("collection", collection);
parseBody();
return finish.get();
}
}
public GazelleV_LeftArrowScript.Evaluable parseIfStatement() {
consume("if");
GazelleV_LeftArrowScript.Evaluable condition, body, elseBranch = null;
{
AutoCloseable __14 = tempAdd(closerTokens, "then");
try {
condition = parseExpr();
} finally {
_close(__14);
}
}
if (consumeOpt("then")) {
AutoCloseable __15 = tempAdd(closerTokens, "else");
try {
body = parseExpr();
if (consumeOpt("else"))
elseBranch = parseExpr();
} finally {
_close(__15);
}
} else {
body = parseCurlyBlock(new BuildingScript());
if (consumeOpt("else")) {
if (is("if"))
elseBranch = parseIfStatement();
else
elseBranch = parseCurlyBlock(new BuildingScript());
}
}
return new GazelleV_LeftArrowScript.IfThen(condition, body, elseBranch);
}
public GazelleV_LeftArrowScript.Evaluable parseRepeatStatement() {
consume("repeat");
var n = parseExpr();
var body = parseCurlyBlock(new BuildingScript());
return new GazelleV_LeftArrowScript.RepeatN(n, body);
}
public void addVar(String var) {
addVar(var, new LASValueDescriptor());
}
public void addVar(String var, LASValueDescriptor type) {
knownVars.put(var, type);
}
public void addVar(String var, Class type, boolean canBeNull) {
addVar(var, typeToValueDescriptor(type, canBeNull));
}
public LASValueDescriptor typeToValueDescriptor(Type type) {
return typeToValueDescriptor(type, true);
}
public LASValueDescriptor typeToValueDescriptor(Type type, boolean canBeNull) {
return type == null ? new LASValueDescriptor() : new LASValueDescriptor.NonExact(typeToClass(type), canBeNull);
}
public Map globalClassNames_cache;
public Map globalClassNames() {
if (globalClassNames_cache == null)
globalClassNames_cache = globalClassNames_load();
return globalClassNames_cache;
}
public Map globalClassNames_load() {
var packages = mapToTreeSet(importedPackages(), pkg -> pkg + ".");
Map out = new HashMap();
for (var fc : functionContainers) if (fc instanceof Class) {
if (isAnonymousClass((Class) fc))
continue;
out.put(shortClassName((Class) fc), className((Class) fc));
}
var classContainers = classContainerPrefixes();
TreeSet classContainerSet = asTreeSet(classContainers);
out.put("List", "java.util.List");
for (var className : classNameResolver().allFullyQualifiedClassNames()) {
if (isAnonymousClassName(className))
continue;
if (!contains(className, '$')) {
String pkg = longestPrefixInTreeSet(className, packages);
if (pkg != null) {
String shortName = dropPrefix(pkg, className);
if (!shortName.contains(".") && !out.containsKey(shortName))
out.put(shortName, className);
}
}
String container = longestPrefixInTreeSet(className, classContainerSet);
if (container != null) {
String shortName = dropPrefix(container, className);
String existing = out.get(shortName);
if (existing != null) {
int priority = indexOf(classContainers, container);
String oldContainer = longestPrefixInTreeSet(existing, classContainerSet);
int oldPriority = indexOf(classContainers, oldContainer);
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
printVars("className", className, "shortName", shortName, "container", container, "priority", priority, "existing", existing, "oldPriority", oldPriority);
if (priority > oldPriority)
continue;
}
out.put(shortName, className);
}
}
for (var __0 : _entrySet(javaxClassShortcuts())) {
var key = __0.getKey();
var val = __0.getValue();
String fullName = out.get(val);
if (fullName != null)
out.put(key, fullName);
}
return out;
}
transient public IF0> importedPackages;
public Collection importedPackages() {
return importedPackages != null ? importedPackages.get() : importedPackages_base();
}
final public Collection importedPackages_fallback(IF0> _f) {
return _f != null ? _f.get() : importedPackages_base();
}
public Collection importedPackages_base() {
return itemPlus("java.lang", standardImports_fullyImportedPackages());
}
public void addClassAlias(String alias, String longName) {
String fullName = globalClassNames().get(longName);
if (fullName != null)
globalClassNames().put(alias, fullName);
}
public List classContainerPrefixes() {
return map(functionContainers, fc -> className(fc) + "$");
}
static public class UnknownObject extends RuntimeException implements IFieldsToList {
public String name;
public UnknownObject() {
}
public UnknownObject(String name) {
this.name = name;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + name + ")";
}
public Object[] _fieldsToList() {
return new Object[] { name };
}
public String getMessage() {
return "Unknown object: " + name;
}
}
static public class ClassNotFound extends UnknownObject {
public ClassNotFound(String className) {
super(className);
}
public String getMessage() {
return "Class not found: " + name;
}
}
public LASClassDef parseClassDef() {
consume("class");
LASClassDef classDef = new LASClassDef();
classDef.verbose(scaffoldingEnabled());
if (nempty(classDefPrefix))
classDef.classDefPrefix(classDefPrefix);
String name = consumeIdentifier();
classDef.userGivenName(name);
if (consumeOpt("is")) {
classDef.interfaces.add(parseType());
}
consume("{");
while (!is("}")) {
if (is(";")) {
next();
continue;
}
if (is("def")) {
AutoCloseable __16 = tempAddKnownVars("this");
try {
GazelleV_LeftArrowScript.FunctionDef fd = parseFunctionDefinition(null);
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
printVars("knownVarsAfterFunctionDef", knownVars);
classDef.methods.add(fd);
continue;
} finally {
_close(__16);
}
}
LASClassDef.FieldDef fd = new LASClassDef.FieldDef();
fd.name(consumeIdentifier());
var type = parseColonType();
fd.type(type);
classDef.fields.add(fd);
}
consume("}");
classDefs.put(name, classDef);
return classDef;
}
public Type parseColonTypeOpt() {
if (is(":"))
return parseColonType();
return null;
}
public Type parseColonType() {
consume(":");
return parseType();
}
public Type parseType() {
String typeName = consumeIdentifier();
Object type = findExternalObject(typeName);
if (!(type instanceof Class))
throw new ClassNotFound(typeName);
return parseArrayType(parseTypeArguments((Type) type));
}
public Type parseArrayType(Type type) {
while (is("[") && is(1, "]")) {
consume(2);
type = new GenericArrayTypeImpl(type);
}
return type;
}
final public Type parseTypeArgumentsOpt(Type type) {
return parseTypeArguments(type);
}
public Type parseTypeArguments(Type type) {
if (is("<") && empty(nextSpace()) && isIdentifier(token(1))) {
next();
List args = new ArrayList();
while (true) {
args.add(parseType());
if (is(">"))
break;
consume(",");
}
consume(">");
if (type != null)
type = new ParameterizedTypeImpl(null, type, toTypedArray(Type.class, args));
}
return type;
}
transient public IF1 classForName;
public Class classForName(String name) {
return classForName != null ? classForName.get(name) : classForName_base(name);
}
final public Class classForName_fallback(IF1 _f, String name) {
return _f != null ? _f.get(name) : classForName_base(name);
}
public Class classForName_base(String name) {
try {
return Class.forName(name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void copyFunctionContainersFrom(GazelleV_LeftArrowScriptParser parser) {
functionContainers = cloneList(parser.functionContainers);
globalClassNames_cache = parser.globalClassNames();
}
public ClassNameResolver classNameResolver() {
if (classNameResolver == null)
classNameResolver = new ClassNameResolver().byteCodePath(assertNotNull(getBytecodePathForClass(this))).init();
return classNameResolver;
}
public GazelleV_LeftArrowScriptParser classNameResolver(ClassNameResolver classNameResolver) {
this.classNameResolver = classNameResolver;
return this;
}
public GazelleV_LeftArrowScript.Evaluable parseStringLiteral() {
return _const(unquote_relaxedMLS(consume()));
}
public void addFunctionDefs(Map map) {
putAll(functionDefs, map);
}
}
static public class Complex implements IFieldsToList {
static final public String _fieldOrder = "re im";
public double re;
public double im;
public Complex() {
}
public Complex(double re, double im) {
this.im = im;
this.re = re;
}
public boolean equals(Object o) {
if (!(o instanceof Complex))
return false;
Complex __1 = (Complex) o;
return re == __1.re && im == __1.im;
}
public int hashCode() {
int h = -1679819632;
h = boostHashCombine(h, _hashCode(re));
h = boostHashCombine(h, _hashCode(im));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { re, im };
}
public double abs() {
return sqrt(re * re + im * im);
}
public double re() {
return re;
}
public double im() {
return im;
}
final public double angle() {
return phase();
}
public double phase() {
return Math.atan2(im, re);
}
public double fracAngle() {
return fracNonNeg(angle() / twoPi());
}
public String toString() {
if (im != 0)
return re == 0 ? im + "i" : re + plusPrefixUnlessMinus(str(im)) + "i";
else
return str(re);
}
}
static public class PingSource {
final public PingSource setAction(IF0 action) {
return action(action);
}
public PingSource action(IF0 action) {
this.action = action;
return this;
}
final public IF0 getAction() {
return action();
}
public IF0 action() {
return action;
}
volatile public IF0 action;
public String text;
public ThreadPool threadPool;
public PingSource() {
}
public PingSource(ThreadPool threadPool) {
this.threadPool = threadPool;
}
public PingSource(ThreadPool threadPool, String text) {
this.text = text;
this.threadPool = threadPool;
}
public PingSource(IF0 action) {
this.action = action;
}
final public boolean get() {
var a = action;
return a != null && a.get();
}
final public void ping() {
var a = action;
if (a != null)
a.get();
}
public void cancel() {
action = new Cancelled();
}
public class Cancelled implements IF0 {
public Boolean get() {
throw new PingSourceCancelledException(PingSource.this);
}
}
public class Encapsulated implements Runnable, IFieldsToList {
public Runnable r;
public Encapsulated() {
}
public Encapsulated(Runnable r) {
this.r = r;
}
public Object[] _fieldsToList() {
return new Object[] { r };
}
public void run() {
try {
try {
pingSource_tl().set(PingSource.this);
ping();
r.run();
} finally {
pingSource_tl().set(null);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return PingSource.this + ": " + r;
}
}
public void dO(Runnable r) {
if (r == null)
return;
threadPool.acquireThreadOrQueue(new Encapsulated(r));
}
public String toString() {
String t = text;
return nempty(t) ? t : super.toString();
}
public ISleeper_v2 sleeper() {
return threadPool.sleeper();
}
}
static public class MultiMap implements IMultiMap {
public Map > data = new HashMap >();
public int fullSize;
public MultiMap() {
}
public MultiMap(boolean useTreeMap) {
if (useTreeMap)
data = new TreeMap();
}
public MultiMap(MultiMap map) {
putAll(map);
}
public MultiMap(Map > data) {
this.data = data;
}
public void put(A key, B value) {
synchronized (data) {
List list = data.get(key);
if (list == null)
data.put(key, list = _makeEmptyList());
list.add(value);
++fullSize;
}
}
public void add(A key, B value) {
put(key, value);
}
public void addAll(A key, Collection values) {
putAll(key, values);
}
public void addAllIfNotThere(A key, Collection values) {
synchronized (data) {
for (B value : values) setPut(key, value);
}
}
public void setPut(A key, B value) {
synchronized (data) {
if (!containsPair(key, value))
put(key, value);
}
}
public boolean containsPair(A key, B value) {
synchronized (data) {
return get(key).contains(value);
}
}
public void putAll(Collection keys, B value) {
synchronized (data) {
for (A key : unnullForIteration(keys)) put(key, value);
}
}
public void putAll(A key, Collection values) {
synchronized (data) {
if (nempty(values))
getActual(key).addAll(values);
}
}
public void putAll(Iterable> pairs) {
synchronized (data) {
for (Pair p : unnullForIteration(pairs)) put(p.a, p.b);
}
}
public void removeAll(A key, Collection values) {
synchronized (data) {
for (B value : values) remove(key, value);
}
}
public List get(A key) {
synchronized (data) {
List list = data.get(key);
return list == null ? Collections.emptyList() : list;
}
}
public List getOpt(A key) {
synchronized (data) {
return data.get(key);
}
}
public List getAndClear(A key) {
synchronized (data) {
List l = cloneList(data.get(key));
remove(key);
return l;
}
}
public List getActual(A key) {
synchronized (data) {
List list = data.get(key);
if (list == null)
data.put(key, list = _makeEmptyList());
return list;
}
}
public void clean(A key) {
synchronized (data) {
List list = data.get(key);
if (list != null && list.isEmpty()) {
fullSize -= l(list);
data.remove(key);
}
}
}
final public Set keys() {
return keySet();
}
public Set keySet() {
synchronized (data) {
return data.keySet();
}
}
public void remove(A key) {
synchronized (data) {
fullSize -= l(this.getOpt(key));
data.remove(key);
}
}
final public void remove(Pair p) {
removePair(p);
}
public void removePair(Pair p) {
if (p != null)
remove(p.a, p.b);
}
public void remove(A key, B value) {
synchronized (data) {
List list = data.get(key);
if (list != null) {
if (list.remove(value))
fullSize--;
if (list.isEmpty())
data.remove(key);
}
}
}
public void clear() {
synchronized (data) {
data.clear();
}
}
public boolean containsKey(A key) {
synchronized (data) {
return data.containsKey(key);
}
}
public B getFirst(A key) {
synchronized (data) {
List list = get(key);
return list.isEmpty() ? null : list.get(0);
}
}
public void addAll(MultiMap map) {
putAll(map);
}
public void putAll(MultiMap map) {
synchronized (data) {
for (A key : map.keySet()) putAll(key, map.get(key));
}
}
public void putAll(Map map) {
synchronized (data) {
if (map != null)
for (Map.Entry e : map.entrySet()) put(e.getKey(), e.getValue());
}
}
final public int keyCount() {
return keysSize();
}
public int keysSize() {
synchronized (data) {
return l(data);
}
}
final public int fullSize() {
return size();
}
public int size() {
synchronized (data) {
return fullSize;
}
}
public List reverseGet(B b) {
synchronized (data) {
List l = new ArrayList();
for (A key : data.keySet()) if (data.get(key).contains(b))
l.add(key);
return l;
}
}
public Map > asMap() {
synchronized (data) {
return cloneMap(data);
}
}
public boolean isEmpty() {
synchronized (data) {
return data.isEmpty();
}
}
public List _makeEmptyList() {
return new ArrayList();
}
public Collection> allLists() {
synchronized (data) {
return new ArrayList(data.values());
}
}
public Collection> values() {
return allLists();
}
public List allValues() {
return concatLists(data.values());
}
public Object mutex() {
return data;
}
public String toString() {
return "mm" + str(data);
}
public Map> innerMap() {
return data;
}
}
static public class SynchronizedSet extends SynchronizedCollection implements Set {
public SynchronizedSet() {
}
public SynchronizedSet(Set s) {
super(s);
}
public SynchronizedSet(Set s, Object mutex) {
super(s, mutex);
}
public boolean equals(Object o) {
if (this == o)
return true;
synchronized (mutex) {
return c.equals(o);
}
}
public int hashCode() {
synchronized (mutex) {
return c.hashCode();
}
}
}
static public class TestCloseableIterableIterator extends CloseableIterableIterator {
public int i;
transient public Set onClosing;
public TestCloseableIterableIterator onClosing(Runnable r) {
onClosing = createOrAddToSyncLinkedHashSet(onClosing, r);
return this;
}
public TestCloseableIterableIterator removeClosingListener(Runnable r) {
main.remove(onClosing, r);
return this;
}
public void closing() {
if (onClosing != null)
for (var listener : onClosing) pcallF_typed(listener);
}
public boolean hasNext() {
return i == 0;
}
public Object next() {
i++;
return null;
}
public void close() {
closing();
}
}
public interface IntSize {
public int size();
}
static public class SynchronizedMap implements Map, Serializable {
public SynchronizedMap() {
}
public Map m;
public Object mutex;
public SynchronizedMap(Map m) {
this.m = Objects.requireNonNull(m);
mutex = this;
}
public SynchronizedMap(Map m, Object mutex) {
this.m = m;
this.mutex = mutex;
}
public Map innerMap() {
return m;
}
public int size() {
synchronized (mutex) {
return m.size();
}
}
public boolean isEmpty() {
synchronized (mutex) {
return m.isEmpty();
}
}
public boolean containsKey(Object key) {
synchronized (mutex) {
return m.containsKey(key);
}
}
public boolean containsValue(Object value) {
synchronized (mutex) {
return m.containsValue(value);
}
}
public V get(Object key) {
synchronized (mutex) {
return m.get(key);
}
}
public V put(K key, V value) {
synchronized (mutex) {
return m.put(key, value);
}
}
public V remove(Object key) {
synchronized (mutex) {
return m.remove(key);
}
}
public void putAll(Map extends K, ? extends V> map) {
synchronized (mutex) {
m.putAll(map);
}
}
public void clear() {
synchronized (mutex) {
m.clear();
}
}
transient public Set keySet;
transient public Set> entrySet;
transient public Collection values;
public Set keySet() {
synchronized (mutex) {
if (keySet == null)
keySet = new SynchronizedSet<>(m.keySet(), mutex);
return keySet;
}
}
public Set> entrySet() {
synchronized (mutex) {
if (entrySet == null)
entrySet = new SynchronizedSet<>(m.entrySet(), mutex);
return entrySet;
}
}
public Collection values() {
synchronized (mutex) {
if (values == null)
values = new SynchronizedCollection<>(m.values(), mutex);
return values;
}
}
public boolean equals(Object o) {
if (this == o)
return true;
synchronized (mutex) {
return m.equals(o);
}
}
public int hashCode() {
synchronized (mutex) {
return m.hashCode();
}
}
public String toString() {
synchronized (mutex) {
return m.toString();
}
}
@Override
public V getOrDefault(Object k, V defaultValue) {
synchronized (mutex) {
return m.getOrDefault(k, defaultValue);
}
}
@Override
public void forEach(BiConsumer super K, ? super V> action) {
synchronized (mutex) {
m.forEach(action);
}
}
@Override
public void replaceAll(BiFunction super K, ? super V, ? extends V> function) {
synchronized (mutex) {
m.replaceAll(function);
}
}
@Override
public V putIfAbsent(K key, V value) {
synchronized (mutex) {
return m.putIfAbsent(key, value);
}
}
@Override
public boolean remove(Object key, Object value) {
synchronized (mutex) {
return m.remove(key, value);
}
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
synchronized (mutex) {
return m.replace(key, oldValue, newValue);
}
}
@Override
public V replace(K key, V value) {
synchronized (mutex) {
return m.replace(key, value);
}
}
@Override
public V computeIfAbsent(K key, java.util.function.Function super K, ? extends V> mappingFunction) {
synchronized (mutex) {
return m.computeIfAbsent(key, mappingFunction);
}
}
@Override
public V computeIfPresent(K key, BiFunction super K, ? super V, ? extends V> remappingFunction) {
synchronized (mutex) {
return m.computeIfPresent(key, remappingFunction);
}
}
@Override
public V compute(K key, BiFunction super K, ? super V, ? extends V> remappingFunction) {
synchronized (mutex) {
return m.compute(key, remappingFunction);
}
}
@Override
public V merge(K key, V value, BiFunction super V, ? super V, ? extends V> remappingFunction) {
synchronized (mutex) {
return m.merge(key, value, remappingFunction);
}
}
@java.io.Serial
private void writeObject(ObjectOutputStream s) throws IOException {
synchronized (mutex) {
s.defaultWriteObject();
}
}
}
static final public class WeakHasherMap extends AbstractMap implements Map {
public Hasher hasher = null;
private boolean keyEquals(Object k1, Object k2) {
return (hasher == null ? k1.equals(k2) : hasher.equals(k1, k2));
}
private int keyHashCode(Object k1) {
return (hasher == null ? k1.hashCode() : hasher.hashCode(k1));
}
private WeakKey WeakKeyCreate(K k) {
if (k == null)
return null;
else
return new WeakKey(k);
}
private WeakKey WeakKeyCreate(K k, ReferenceQueue super K> q) {
if (k == null)
return null;
else
return new WeakKey(k, q);
}
final public class WeakKey extends WeakReference {
public int hash;
public WeakKey(K k) {
super(k);
hash = keyHashCode(k);
}
private WeakKey create(K k) {
if (k == null)
return null;
else
return new WeakKey(k);
}
public WeakKey(K k, ReferenceQueue super K> q) {
super(k, q);
hash = keyHashCode(k);
}
private WeakKey create(K k, ReferenceQueue super K> q) {
if (k == null)
return null;
else
return new WeakKey(k, q);
}
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o.getClass().equals(WeakKey.class)))
return false;
Object t = this.get();
@SuppressWarnings("unchecked")
Object u = ((WeakKey) o).get();
if ((t == null) || (u == null))
return false;
if (t == u)
return true;
return keyEquals(t, u);
}
@Override
public int hashCode() {
return hash;
}
}
public HashMap hash;
public ReferenceQueue super K> queue = new ReferenceQueue();
@SuppressWarnings("unchecked")
private void processQueue() {
WeakKey wk;
while ((wk = (WeakKey) queue.poll()) != null) {
hash.remove(wk);
}
}
public WeakHasherMap(int initialCapacity, float loadFactor) {
hash = new HashMap(initialCapacity, loadFactor);
}
public WeakHasherMap(int initialCapacity) {
hash = new HashMap(initialCapacity);
}
public WeakHasherMap() {
hash = new HashMap();
}
public WeakHasherMap(Hasher h) {
hash = new HashMap();
hasher = h;
}
@Override
public int size() {
return entrySet().size();
}
@Override
public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override
public boolean containsKey(Object key) {
@SuppressWarnings("unchecked")
K kkey = (K) key;
return hash.containsKey(WeakKeyCreate(kkey));
}
@Override
public V get(Object key) {
@SuppressWarnings("unchecked")
K kkey = (K) key;
return hash.get(WeakKeyCreate(kkey));
}
@Override
public V put(K key, V value) {
processQueue();
return hash.put(WeakKeyCreate(key, queue), value);
}
@Override
public V remove(Object key) {
processQueue();
@SuppressWarnings("unchecked")
K kkey = (K) key;
return hash.remove(WeakKeyCreate(kkey));
}
@Override
public void clear() {
processQueue();
hash.clear();
}
@SuppressWarnings("TypeParameterShadowing")
final public class Entry implements Map.Entry {
public Map.Entry ent;
public K key;
public Entry(Map.Entry ent, K key) {
this.ent = ent;
this.key = key;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return ent.getValue();
}
@Override
public V setValue(V value) {
return ent.setValue(value);
}
private boolean keyvalEquals(K o1, K o2) {
return (o1 == null) ? (o2 == null) : keyEquals(o1, o2);
}
private boolean valEquals(V o1, V o2) {
return (o1 == null) ? (o2 == null) : o1.equals(o2);
}
@SuppressWarnings("NonOverridingEquals")
public boolean equals(Map.Entry e) {
return (keyvalEquals(key, e.getKey()) && valEquals(getValue(), e.getValue()));
}
@Override
public int hashCode() {
V v;
return (((key == null) ? 0 : keyHashCode(key)) ^ (((v = getValue()) == null) ? 0 : v.hashCode()));
}
}
final public class EntrySet extends AbstractSet> {
public Set> hashEntrySet = hash.entrySet();
@Override
public Iterator