Warning : session_start(): open(/var/lib/php/sessions/sess_evcqcjb29fn1uqdd7bues74taj, 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 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.awt.geom.*;
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 Object leftArrowVerbose(LASClassLoader lasClassLoader, String script) {
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
parser.lasClassLoader(lasClassLoader);
return leftArrowVerbose(parser, script);
}
static public Object leftArrowVerbose(String script) {
return leftArrowVerbose(new GazelleV_LeftArrowScriptParser(), script);
}
static public Object leftArrowVerbose(GazelleV_LeftArrowScriptParser parser, String script) {
if (parser.lasClassLoader() != null)
parser.lasClassLoader().rememberClassBytes(true);
enableScaffolding(parser);
parser.allowTheWorld();
var parsedScript = parser.parse(script);
parser.printFunctionDefs(parsedScript);
print(parsedScript);
print("leftArrowVerbose:\n" + GazelleV_LeftArrowScript.indentedScriptStruct(parsedScript));
FlexibleVarContext ctx = new FlexibleVarContext();
var result = parsedScript.get(ctx);
ctx.printMe();
return result;
}
static public A enableScaffolding(A o) {
return enableScaffolding(o, true);
}
static public A enableScaffolding(A o, boolean b) {
if (o instanceof IMeta)
((IMeta) o).metaPut("scaffolding", trueOrNull(b));
return o;
}
static volatile public StringBuffer local_log = new StringBuffer();
static public boolean printAlsoToSystemOut = true;
static volatile public Appendable print_log = local_log;
static volatile public int print_log_max = 1024 * 1024;
static volatile public int local_log_max = 100 * 1024;
static public boolean print_silent = false;
static public Object print_byThread_lock = new Object();
static volatile public ThreadLocal print_byThread;
static volatile public Object print_allThreads;
static volatile public Object print_preprocess;
static public void print() {
print("");
}
static public A print(String s, A o) {
print(combinePrintParameters(s, o));
return o;
}
static public A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = o + "\n";
print_noNewLine(s);
return o;
}
static public void print_noNewLine(String s) {
try {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
} catch (Throwable e) {
System.out.println(getStackTrace(e));
}
print_raw(s);
}
static public void print_raw(String s) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
if (printAlsoToSystemOut)
System.out.print(s);
vmBus_send("printed", mc(), s);
}
static public void print_autoRotate() {
}
static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public Boolean trueOrNull(Boolean b) {
return eq(b, false) ? null : b;
}
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 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 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 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 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 boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
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 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 A or(A a, A b) {
return a != null ? a : b;
}
static public Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
static public Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
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 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 Object invokeMethod(Method m, Object o, Object... args) {
try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != l(args)) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
static public Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static public Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static public Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static 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 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 vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
static public void pcallFAll_minimalExceptionHandling(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
ping();
pcallF_minimalExceptionHandling(f, args);
}
}
static public void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) {
while (it.hasNext()) {
ping();
pcallF_minimalExceptionHandling(it.next(), args);
}
}
static public Set vm_busListeners_live_cache;
static public Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
static public Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static public Map vm_busListenersByMessage_live_cache;
static public Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
static public Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static public AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null)
return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
static public 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 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 isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
static public boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
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 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 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 Collections.synchronizedMap(map);
}
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 RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
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 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 void _handleError(Error e) {
}
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 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 Object pcallF_minimalExceptionHandling(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable e) {
System.out.println(getStackTrace(e));
_storeException(e);
}
return null;
}
static public Set vm_generalIdentityHashSet(Object name) {
synchronized (vm_generalMap()) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = syncIdentityHashSet());
return set;
}
}
static public Map vm_generalHashMap(Object name) {
synchronized (vm_generalMap()) {
Map m = (Map) (vm_generalMap_get(name));
if (m == null)
vm_generalMap_put(name, m = syncHashMap());
return m;
}
}
static public A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
static public 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 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 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 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 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 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 Collections.synchronizedList(l);
}
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 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());
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return strOrEmpty(first((Collection) strings));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(strOrEmpty(i.next()));
while (i.hasNext()) buf.append(glue).append(strOrEmpty(i.next()));
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(String glue, Object... strings) {
return join(glue, Arrays.asList(strings));
}
static public String join(Iterable strings) {
return join("", strings);
}
static public String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static public String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static public 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 ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(char[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (var i : a) l.add(i);
return l;
}
static public ArrayList asList(byte[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (var i : a) l.add(i);
return l;
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(long[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static public ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static public ArrayList asList(double[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static public ArrayList asList(short[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (short i : a) l.add(i);
return l;
}
static public ArrayList asList(Iterator it) {
ArrayList l = new ArrayList();
if (it != null)
while (it.hasNext()) l.add(it.next());
return l;
}
static public ArrayList asList(IterableIterator s) {
return asList((Iterator) s);
}
static public ArrayList asList(Iterable s) {
if (s instanceof ArrayList)
return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s) l.add(a);
return l;
}
static public ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null)
while ((a = p.next()) != null) l.add(a);
return l;
}
static public ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public ArrayList asList(ReverseChain c) {
return c == null ? emptyList() : c.toList();
}
static public List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
static 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 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 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 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_get(Object key) {
return vm_generalMap().get(key);
}
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 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 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 String joinWithComma(Iterable 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 String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public Pair first(Map map) {
return mapEntryToPair(first(entrySet(map)));
}
static public Pair first(MultiMap mm) {
if (mm == null)
return null;
var e = first(mm.data.entrySet());
if (e == null)
return null;
return pair(e.getKey(), first(e.getValue()));
}
static public A first(IterableIterator i) {
return first((Iterator ) i);
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public Character first(CharSequence s) {
return empty(s) ? null : s.charAt(0);
}
static public A first(Pair p) {
return p == null ? null : p.a;
}
static public A first(T3 t) {
return t == null ? null : t.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public Double first(double[] l) {
return empty(l) ? null : l[0];
}
static public A first(A[] l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(Iterable l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(IF1 pred, Iterable l) {
return firstThat(pred, l);
}
static public A first(AppendableChain a) {
return a == null ? null : a.element;
}
static public 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 List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
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 boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
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 int strL(String s) {
return s == null ? 0 : s.length();
}
static public int listL(Collection l) {
return l == null ? 0 : l.size();
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static public 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 String className(Object o) {
return getClassName(o);
}
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 Collections.synchronizedSet(set);
}
static public Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
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 HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
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 Pair mapEntryToPair(Map.Entry e) {
return e == null ? null : pair(e.getKey(), e.getValue());
}
static public Set> entrySet(Map map) {
return _entrySet(map);
}
static public A firstThat(Iterable l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(A[] l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static public A firstThat(IF1 pred, A[] l) {
return firstThat(l, pred);
}
static public 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 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 int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
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 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 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 Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
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 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 boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
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 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 FlexibleVarContext extends VarContext {
public Map vars;
public FlexibleVarContext() {
}
public FlexibleVarContext(VarContext parent) {
super(parent);
}
public Object get(String name) {
if (containsKey(vars, name))
return mapGet(vars, name);
if (parent != null)
return parent.get(name);
return null;
}
public void set(String name, Object value) {
vars = putOrCreateSyncMap(vars, name, value);
}
public AutoCloseable tempSet(String name, Object value) {
initMap();
return main.tempPut(vars, name, value);
}
public void unset(String name) {
remove(vars, name);
}
public Map varMap() {
return vars;
}
final public void initMap() {
makeThreadSafe();
}
public void makeThreadSafe() {
if (vars == null)
vars = syncHashMap();
}
}
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 interface IMeta {
public void _setMeta(Object meta);
public Object _getMeta();
default public IAutoCloseableF0 _tempMetaMutex() {
return new IAutoCloseableF0() {
public Object get() {
return IMeta.this;
}
public void close() {
}
};
}
default public Object getMeta(Object obj, Object key) {
return metaGet(obj, key);
}
default public Object metaGet(Object obj, Object key) {
return metaMapGet(obj, key);
}
default public Object metaGet(String key, Object obj) {
return metaMapGet(obj, key);
}
default public Object getMeta(Object key) {
return metaGet(key);
}
default public Object metaGet(Object key) {
if (key == null)
return null;
Object meta = _getMeta();
if (meta instanceof Map)
return ((Map) meta).get(key);
return null;
}
default public void metaSet(IMeta obj, Object key, Object value) {
metaPut(obj, key, value);
}
default public void metaPut(IMeta obj, Object key, Object value) {
metaMapPut(obj, key, value);
}
default public void metaSet(Object key, Object value) {
metaPut(key, value);
}
default public void metaPut(Object key, Object value) {
if (key == null)
return;
Map map = convertObjectMetaToMap(this);
syncMapPutOrRemove(map, key, value);
}
}
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 LASClassLoader extends InMemoryClassLoader implements ILASClassLoader {
public Map definedClasses = new HashMap();
public Lock lock = lock();
public LASClassLoader(ClassLoader parent) {
super(parent);
}
public LASClassLoader(Class parent) {
super(parent.getClassLoader());
}
public Class> defineLASClass(String name, IF0 generateClass) {
Lock __0 = lock;
lock(__0);
try {
try {
return loadClass(name);
} catch (ClassNotFoundException e) {
print("Generating class " + name);
return defineAClass(name, generateClass.get());
}
} finally {
unlock(__0);
}
}
}
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 setSourceInfo(Object sourceInfo) {
return sourceInfo(sourceInfo);
}
public GazelleV_LeftArrowScriptParser sourceInfo(Object sourceInfo) {
this.sourceInfo = sourceInfo;
return this;
}
final public Object getSourceInfo() {
return sourceInfo();
}
public Object sourceInfo() {
return sourceInfo;
}
public Object sourceInfo;
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();
public Set flags = ciSet();
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 __19 = (EvaluableWrapper) o;
return eq(expr, __19.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);
}
}
{
tokenize = text -> {
List tok = tokenize_base(text);
preprocess(tok);
return tok;
};
}
public void preprocess(List tok) {
tok_ifdef(tok, __18 -> getFlag(__18));
tok_pcall_script(tok);
tok_script_settable(tok);
}
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(spaceCombine(sourceInfo, lineAndColumn(-1))));
}
}
public void parseScript_2(BuildingScript script) {
AutoCloseable __9 = 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(__9);
}
}
public GazelleV_LeftArrowScript.Evaluable parseParamDecl(BuildingScript script) {
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;
}
public GazelleV_LeftArrowScript.Evaluable parseInstruction(BuildingScript script) {
if (consumeOpt("param"))
return parseParamDecl(script);
if (is("throw")) {
consume();
return new GazelleV_LeftArrowScript.Throw(parseExpr());
}
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 (consumeOpt("continue")) {
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);
}
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 linkToSrc(() -> 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 (consumeOpt("try")) {
GazelleV_LeftArrowScript.Evaluable body = parseCurlyBlock();
while (consumeOpt("catch")) {
String var = consumeIdentifierOpt();
AutoCloseable __10 = tempAddKnownVars(var);
try {
GazelleV_LeftArrowScript.Evaluable catchBlock = parseCurlyBlock();
body = new GazelleV_LeftArrowScript.TryCatch(body, var, catchBlock);
} finally {
_close(__10);
}
}
if (consumeOpt("finally")) {
GazelleV_LeftArrowScript.Evaluable finallyBlock = parseCurlyBlock();
return new GazelleV_LeftArrowScript.TryFinally(body, finallyBlock);
}
return body;
}
if (is("def")) {
var fd = parseFunctionDefinition(currentReturnableScript.functionDefs);
return new GazelleV_LeftArrowScript.Const(fd);
}
if (is("{"))
return parseCurlyBlock();
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(cd.resolvable(lasClassLoader));
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, "class")) {
unconsume();
return new GazelleV_LeftArrowScript.ClassDef(parseClassDef().resolvable(lasClassLoader));
}
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 (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
printVars("parseExprStartingWithClass", "c", 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) {
if (!isStaticField(field))
throw fail(field + " is not a static field");
if (consumeLeftArrowOpt()) {
GazelleV_LeftArrowScript.Evaluable rhs = parseExpr();
return new GazelleV_LeftArrowScript.SetStaticField(field, rhs);
}
assertCmdEnd();
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 __11 = 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(__11);
}
}
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 (consumeLeftArrowOpt()) {
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;
}
if (is("!") && is(1, "_getField_")) {
next(2);
String field = consumeIdentifier();
return new GazelleV_LeftArrowScript.GetField(target, field);
}
return target;
}
public boolean consumeLeftArrowOpt() {
if (is("<") && eq(token(1), "-")) {
next(2);
return true;
}
return false;
}
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)
if (((IHasTokenRangeWithSrc) a).tokenRangeWithSrc() == null)
((IHasTokenRangeWithSrc) a).setTokenRangeWithSrc(new TokenRangeWithSrc(start, ptr().plus(-1)).sourceInfo(sourceInfo()));
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);
}
return findExternalObject2(name);
}
transient public IF1 findExternalObject2;
public Object findExternalObject2(String name) {
return findExternalObject2 != null ? findExternalObject2.get(name) : findExternalObject2_base(name);
}
final public Object findExternalObject2_fallback(IF1 _f, String name) {
return _f != null ? _f.get(name) : findExternalObject2_base(name);
}
public Object findExternalObject2_base(String name) {
String fullName = globalClassNames().get(name);
if (fullName != null)
return classForName(fullName);
{
var __8 = classForNameOpt_noCache(name);
if (__8 != null)
return __8;
}
for (var container : unnullForIteration(functionContainers)) {
if (hasMethodNamed(container, name) && !isBlockedFunctionContainerMethod(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;
}
transient public IF2 isBlockedFunctionContainerMethod;
public boolean isBlockedFunctionContainerMethod(Object container, String name) {
return isBlockedFunctionContainerMethod != null ? isBlockedFunctionContainerMethod.get(container, name) : isBlockedFunctionContainerMethod_base(container, name);
}
final public boolean isBlockedFunctionContainerMethod_fallback(IF2 _f, Object container, String name) {
return _f != null ? _f.get(container, name) : isBlockedFunctionContainerMethod_base(container, name);
}
public boolean isBlockedFunctionContainerMethod_base(Object container, String name) {
return false;
}
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(nonNulls(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) {
var start = ptr();
consume("def");
String functionName = assertIdentifier(tpp());
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
print("parseFunctionDefinition " + functionName);
return parseFunctionDefinition_step2(functionDefsToAddTo, start, functionName);
}
public GazelleV_LeftArrowScript.FunctionDef parseFunctionDefinition_step2(Map functionDefsToAddTo, ListAndIndex start, String functionName) {
LinkedHashMap args = new LinkedHashMap();
while (parseFunctionDefArg(args) != null) {
}
var returnType = parseColonTypeOpt();
var fd = new GazelleV_LeftArrowScript.FunctionDef(functionName, keysList(args), null);
fd.argTypes(valuesArray(LASValueDescriptor.class, args));
{
if (functionDefsToAddTo != null)
functionDefsToAddTo.put(functionName, fd);
}
var scope = newScope();
scope.useFixedVars(useFixedVarContexts);
AutoCloseable __12 = tempScope(scope);
try {
AutoCloseable __13 = 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 linkToSrc(start, fd);
} finally {
_close(__13);
}
} finally {
_close(__12);
}
}
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() {
return parseCurlyBlock(new BuildingScript());
}
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 __14 = tempAddKnownVars(vars);
try {
body = parseCurlyBlock(new BuildingScript().isLoopBody(true));
} finally {
_close(__14);
}
}
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 __15 = tempAdd(closerTokens, "then");
try {
condition = parseExpr();
} finally {
_close(__15);
}
}
if (consumeOpt("then")) {
AutoCloseable __16 = tempAdd(closerTokens, "else");
try {
body = parseExpr();
if (consumeOpt("else"))
elseBranch = parseExpr();
} finally {
_close(__16);
}
} else {
body = parseCurlyBlock();
if (consumeOpt("else")) {
if (is("if"))
elseBranch = parseIfStatement();
else
elseBranch = parseCurlyBlock();
}
}
return new GazelleV_LeftArrowScript.IfThen(condition, body, elseBranch);
}
public GazelleV_LeftArrowScript.Evaluable parseRepeatStatement() {
consume("repeat");
var n = parseExpr();
var body = parseCurlyBlock();
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 name : importedClasses()) out.put(shortenClassName(name), name);
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());
}
transient public IF0> importedClasses;
public Collection importedClasses() {
return importedClasses != null ? importedClasses.get() : importedClasses_base();
}
final public Collection importedClasses_fallback(IF0> _f) {
return _f != null ? _f.get() : importedClasses_base();
}
public Collection importedClasses_base() {
return standardImports_singleClasses();
}
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() {
return linkToSrc(() -> {
consume("class");
LASClassDef classDef = new LASClassDef();
classDef.verbose(scaffoldingEnabled());
if (nempty(classDefPrefix))
classDef.classDefPrefix(classDefPrefix);
String name = consumeIdentifier();
classDef.userGivenName(name);
classDefs.put(name, classDef);
if (consumeOpt("extends")) {
classDef.superClass(parseType());
}
if (consumeOpt("is"))
classDef.interfaces.add(parseType());
consume("{");
AutoCloseable __17 = tempAddKnownVars("this");
try {
while (!is("}")) {
if (is(";")) {
next();
continue;
}
if (is("def")) {
GazelleV_LeftArrowScript.FunctionDef fd = parseFunctionDefinition(null);
if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled())
printVars("knownVarsAfterFunctionDef", knownVars);
classDef.methods.add(fd);
continue;
}
var start = ptr();
if (consumeOpt("ctor")) {
var fd = parseFunctionDefinition_step2(null, start, "");
fd.returnType(void.class);
classDef.methods.add(fd);
continue;
}
if (consumeOpt("initializer")) {
classDef.initializers.add(parseCurlyBlock());
continue;
}
LASClassDef.FieldDef fd = new LASClassDef.FieldDef();
fd.name(consumeIdentifier());
var type = parseColonType();
fd.type(type);
if (is(0, "<") && is(1, "-")) {
next(2);
fd.initializer(parseExpr());
}
classDef.addField(fd);
}
consume("}");
return classDef;
} finally {
_close(__17);
}
});
}
public Type parseColonTypeOpt() {
if (is(":"))
return parseColonType();
return null;
}
public Type parseColonType() {
consume(":");
return parseType();
}
public Type findType(String typeName) {
LASClassDef cd = classDefs.get(typeName);
if (cd != null)
return cd.resolvable(lasClassLoader);
Object o = findExternalObject(typeName);
if (o instanceof Class)
return ((Class) o);
throw new ClassNotFound(typeName);
}
public Type parseType() {
String typeName = consumeIdentifier();
Type type = findType(typeName);
return parseArrayType(parseTypeArguments(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();
isBlockedFunctionContainerMethod = parser.isBlockedFunctionContainerMethod;
}
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);
}
public GazelleV_LeftArrowScriptParser setFlag(String flag) {
flags.add(flag);
return this;
}
public boolean getFlag(String flag) {
return flags.contains(flag);
}
}
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;
}
}
public interface IntSize {
public int size();
default public boolean isEmpty() {
return size() == 0;
}
}
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> iterator() {
return new Iterator>() {
public Iterator> hashIterator = hashEntrySet.iterator();
public Map.Entry next = null;
@Override
public boolean hasNext() {
while (hashIterator.hasNext()) {
Map.Entry ent = hashIterator.next();
WeakKey wk = ent.getKey();
K k = null;
if ((wk != null) && ((k = wk.get()) == null)) {
continue;
}
next = new Entry(ent, k);
return true;
}
return false;
}
@Override
public Map.Entry next() {
if ((next == null) && !hasNext())
throw new NoSuchElementException();
Map.Entry e = next;
next = null;
return e;
}
@Override
public void remove() {
hashIterator.remove();
}
};
}
@Override
public boolean isEmpty() {
return !(iterator().hasNext());
}
@Override
public int size() {
int j = 0;
for (Iterator> i = iterator(); i.hasNext(); i.next()) j++;
return j;
}
@Override
public boolean remove(Object o) {
processQueue();
if (!(o instanceof Map.Entry, ?>))
return false;
@SuppressWarnings("unchecked")
Map.Entry e = (Map.Entry) o;
Object ev = e.getValue();
WeakKey wk = WeakKeyCreate(e.getKey());
Object hv = hash.get(wk);
if ((hv == null) ? ((ev == null) && hash.containsKey(wk)) : hv.equals(ev)) {
hash.remove(wk);
return true;
}
return false;
}
@Override
public int hashCode() {
int h = 0;
for (Iterator> i = hashEntrySet.iterator(); i.hasNext(); ) {
Map.Entry ent = i.next();
WeakKey wk = ent.getKey();
Object v;
if (wk == null)
continue;
h += (wk.hashCode() ^ (((v = ent.getValue()) == null) ? 0 : v.hashCode()));
}
return h;
}
}
public Set> entrySet = null;
@Override
public Set> entrySet() {
if (entrySet == null)
entrySet = new EntrySet();
return entrySet;
}
public K findKey(Object key) {
processQueue();
K kkey = (K) key;
WeakKey wkey = WeakKeyCreate(kkey);
WeakKey found = hashMap_findKey(hash, wkey);
return found == null ? null : found.get();
}
}
static public class Pair implements Comparable> {
final public Pair setA(A a) {
return a(a);
}
public Pair a(A a) {
this.a = a;
return this;
}
final public A getA() {
return a();
}
public A a() {
return a;
}
public A a;
final public Pair setB(B b) {
return b(b);
}
public Pair b(B b) {
this.b = b;
return this;
}
final public B getB() {
return b();
}
public B b() {
return b;
}
public B b;
public Pair() {
}
public Pair(A a, B b) {
this.b = b;
this.a = a;
}
public int hashCode() {
return hashCodeFor(a) + 2 * hashCodeFor(b);
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Pair))
return false;
Pair t = (Pair) o;
return eq(a, t.a) && eq(b, t.b);
}
public String toString() {
return "<" + a + ", " + b + ">";
}
public int compareTo(Pair p) {
if (p == null)
return 1;
int i = ((Comparable ) a).compareTo(p.a);
if (i != 0)
return i;
return ((Comparable) b).compareTo(p.b);
}
}
static public class Fail extends RuntimeException implements IFieldsToList {
public Object[] objects;
public Fail() {
}
public Fail(Object... objects) {
this.objects = objects;
}
public Object[] _fieldsToList() {
return new Object[] { objects };
}
public Fail(Throwable cause, Object... objects) {
super(cause);
this.objects = objects;
}
public String toString() {
return joinNemptiesWithColon("Fail", getMessage());
}
public String getMessage() {
return commaCombine(getCause(), objects);
}
}
static abstract public class F0 {
abstract public A get();
}
static abstract public class F1 {
abstract public B get(A a);
}
static abstract public class IterableIterator implements Iterator , Iterable {
public Iterator iterator() {
return this;
}
public void remove() {
unsupportedOperation();
}
}
public static interface IF0 {
public A get();
}
static public interface Hasher {
public int hashCode(A a);
public boolean equals(A a, A b);
}
static public interface IF1 {
public B get(A a);
}
static public class PersistableThrowable extends DynamicObject {
public String className;
public String msg;
public String stacktrace;
final public PersistableThrowable setActualThrowable(Throwable actualThrowable) {
return actualThrowable(actualThrowable);
}
public PersistableThrowable actualThrowable(Throwable actualThrowable) {
this.actualThrowable = actualThrowable;
return this;
}
final public Throwable getActualThrowable() {
return actualThrowable();
}
public Throwable actualThrowable() {
return actualThrowable;
}
transient public Throwable actualThrowable;
public PersistableThrowable() {
}
public PersistableThrowable(Throwable e) {
actualThrowable = e;
if (e == null)
className = "Crazy Null Error";
else {
className = getClassName(e).replace('/', '.');
msg = e.getMessage();
stacktrace = getStackTrace_noRecord(e);
}
}
public String toString() {
return nempty(msg) ? className + ": " + msg : className;
}
public RuntimeException asRuntimeException() {
if (actualThrowable != null)
return main.asRuntimeException(actualThrowable);
return new Fail(this);
}
}
static public interface IVF1 {
public void get(A a);
}
static public class GazelleV_LeftArrowScript {
abstract static public class Base extends HasTokenRangeWithSrc {
public RuntimeException rethrowWithSrc(Throwable e) {
return rethrowWithSrc("", e);
}
public RuntimeException rethrowWithSrc(String msg, Throwable e) {
if (tokenRangeWithSrc() != null)
throw new ScriptError(tokenRangeWithSrc(), msg, e);
else
throw rethrow(e);
}
public String indented() {
return indentedScriptStruct(this);
}
}
static public class ScriptError extends RuntimeException implements IHasTokenRangeWithSrc {
public ScriptError(TokenRangeWithSrc src, Throwable reason) {
super(reason);
tokenRangeWithSrc(src);
}
public ScriptError(TokenRangeWithSrc src, String msg, Throwable reason) {
super(msg, reason);
tokenRangeWithSrc(src);
}
final public ScriptError setTokenRangeWithSrc(TokenRangeWithSrc tokenRangeWithSrc) {
return tokenRangeWithSrc(tokenRangeWithSrc);
}
public ScriptError tokenRangeWithSrc(TokenRangeWithSrc tokenRangeWithSrc) {
this.tokenRangeWithSrc = tokenRangeWithSrc;
return this;
}
final public TokenRangeWithSrc getTokenRangeWithSrc() {
return tokenRangeWithSrc();
}
public TokenRangeWithSrc tokenRangeWithSrc() {
return tokenRangeWithSrc;
}
public TokenRangeWithSrc tokenRangeWithSrc;
public TokenRangeWithSrc src() {
return tokenRangeWithSrc();
}
public String toString() {
return super.toString() + "\n " + src() + " {{ " + shorten(nlToSpace(src().text())) + " }}";
}
}
public interface Evaluable extends IF0, IHasTokenRangeWithSrc {
public default Object get() {
return get(new FlexibleVarContext());
}
public Object get(VarContext ctx);
public default LASValueDescriptor returnType() {
return null;
}
public default Evaluable optimize() {
return this;
}
public default Evaluable optimizeForReturnValueNotNeeded() {
return this;
}
}
abstract static public class EvaluableBase extends Base implements Evaluable {
final public EvaluableBase setReturnType(LASValueDescriptor returnType) {
return returnType(returnType);
}
public EvaluableBase returnType(LASValueDescriptor returnType) {
this.returnType = returnType;
return this;
}
final public LASValueDescriptor getReturnType() {
return returnType();
}
public LASValueDescriptor returnType() {
return returnType;
}
public LASValueDescriptor returnType;
public boolean returnValueNeeded = true;
public Evaluable optimizeForReturnValueNotNeeded() {
returnValueNeeded = false;
return optimize();
}
}
static public AtomicLong scriptIDCounter = new AtomicLong();
static public long scriptID() {
return incAtomicLong(scriptIDCounter);
}
static public class ListFromScript extends EvaluableBase implements IFieldsToList {
public Script script;
public ListFromScript() {
}
public ListFromScript(Script script) {
this.script = script;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + script + ")";
}
public Object[] _fieldsToList() {
return new Object[] { script };
}
public Object get(VarContext ctx) {
return script.getAsList(ctx);
}
}
static public class Script extends EvaluableBase {
transient public long id = scriptID();
public Map functionDefs;
public Evaluable[] steps;
final public Script setScope(LASScope scope) {
return scope(scope);
}
public Script scope(LASScope scope) {
this.scope = scope;
return this;
}
final public LASScope getScope() {
return scope();
}
public LASScope scope() {
return scope;
}
public LASScope scope;
public Map params;
public Script() {
}
public Script(List steps) {
this.steps = toTypedArray(Evaluable.class, steps);
}
public Object get(VarContext ctx) {
Object result = null;
var pingSource = pingSource();
for (var step : steps) {
ping(pingSource);
result = step.get(ctx);
var exiting = ctx.exitFromScript;
if (exiting != null) {
if (exiting == this) {
ctx.exitFromScript = null;
result = ctx.returnValue;
ctx.returnValue(null);
return result;
}
return null;
}
}
return result;
}
public Object getAsList(VarContext ctx) {
Object result = null;
var pingSource = pingSource();
List list = new ArrayList();
for (var step : steps) {
ping(pingSource);
list.add(step.get(ctx));
var exiting = ctx.exitFromScript;
if (exiting != null) {
if (exiting == this) {
ctx.exitFromScript = null;
result = ctx.returnValue;
ctx.returnValue(null);
list.add(result);
return list;
}
return null;
}
}
return list;
}
public String toStringLong() {
return pnlToLines(steps);
}
public String toString() {
return "Script " + n2(id);
}
public FunctionDef getFunction(String name) {
return mapGet(functionDefs, name);
}
final public Script optimize() {
return optimizeScript();
}
public Script optimizeScript() {
int n = returnValueNeeded ? steps.length - 1 : steps.length;
for (int i = 0; i < n; i++) steps[i] = steps[i].optimizeForReturnValueNotNeeded();
for (var f : values(functionDefs)) f.optimize();
return this;
}
}
static public class FunctionDef extends Base implements IFieldsToList {
public String name;
public String[] args;
public Script body;
public FunctionDef() {
}
public FunctionDef(String name, String[] args, Script body) {
this.body = body;
this.args = args;
this.name = name;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + name + ", " + args + ", " + body + ")";
}
public Object[] _fieldsToList() {
return new Object[] { name, args, body };
}
final public FunctionDef setScope(LASScope scope) {
return scope(scope);
}
public FunctionDef scope(LASScope scope) {
this.scope = scope;
return this;
}
final public LASScope getScope() {
return scope();
}
public LASScope scope() {
return scope;
}
public LASScope scope;
final public FunctionDef setReturnType(Type returnType) {
return returnType(returnType);
}
public FunctionDef returnType(Type returnType) {
this.returnType = returnType;
return this;
}
final public Type getReturnType() {
return returnType();
}
public Type returnType() {
return returnType;
}
public Type returnType = Object.class;
final public FunctionDef setArgTypes(LASValueDescriptor[] argTypes) {
return argTypes(argTypes);
}
public FunctionDef argTypes(LASValueDescriptor[] argTypes) {
this.argTypes = argTypes;
return this;
}
final public LASValueDescriptor[] getArgTypes() {
return argTypes();
}
public LASValueDescriptor[] argTypes() {
return argTypes;
}
public LASValueDescriptor[] argTypes;
public FunctionDef(String name, List args, Script body) {
this.args = toStringArray(args);
this.body = body;
this.name = name;
}
public Object callFromOutside(Object... args) {
return call(new FlexibleVarContext(), args);
}
public Object call(VarContext ctx, Object... args) {
VarContext ctx2 = scope != null && scope.useFixedVars ? new FixedVarContext(ctx, scope.names) : new FlexibleVarContext(ctx);
int n = min(l(args), l(this.args));
for (int i = 0; i < n; i++) ctx2.put(this.args[i], args[i]);
return body.get(ctx2);
}
public void optimize() {
body = body.optimize();
}
public boolean isConstructor() {
return eq(name, "");
}
}
static public class Assignment extends EvaluableBase implements IFieldsToList {
public String var;
public Evaluable expression;
public Assignment() {
}
public Assignment(String var, Evaluable expression) {
this.expression = expression;
this.var = var;
}
public Object[] _fieldsToList() {
return new Object[] { var, expression };
}
public Object get(VarContext ctx) {
Object o = expression.get(ctx);
ctx.set(var, o);
return o;
}
public String toString() {
return var + " <- " + expression;
}
}
abstract static public class FixedVarBase extends EvaluableBase {
final public FixedVarBase setScope(LASScope scope) {
return scope(scope);
}
public FixedVarBase scope(LASScope scope) {
this.scope = scope;
return this;
}
final public LASScope getScope() {
return scope();
}
public LASScope scope() {
return scope;
}
public LASScope scope;
public String var;
public int varIdx;
public String varToStr() {
return var + " [" + varIdx + "]";
}
public void assertResolved() {
if (varIdx < 0)
throw fail("Unresolved variable access: " + var);
}
public void resolve() {
varIdx = scope.resolveVar(var);
}
}
static public class FixedVarAssignment extends FixedVarBase {
public FixedVarAssignment() {
}
public Evaluable expression;
public FixedVarAssignment(LASScope scope, String var, Evaluable expression) {
this.expression = expression;
this.var = var;
this.scope = scope;
}
public Object get(VarContext ctx) {
Object o = expression.get(ctx);
((FixedVarContext) ctx).set(varIdx, o);
return o;
}
public String toString() {
return varToStr() + " <- " + expression;
}
}
static public class VarDeclaration extends EvaluableBase implements IFieldsToList {
public String var;
public Class type;
public Evaluable expression;
public VarDeclaration() {
}
public VarDeclaration(String var, Class type, Evaluable expression) {
this.expression = expression;
this.type = type;
this.var = var;
}
public Object[] _fieldsToList() {
return new Object[] { var, type, expression };
}
public Object get(VarContext ctx) {
Object o = expression == null ? null : expression.get(ctx);
ctx.set(var, o);
return o;
}
public String toString() {
return "var " + var + " <- " + expression;
}
}
static public class AssignmentToOuterVar extends EvaluableBase implements IFieldsToList {
public String var;
public Evaluable expression;
public AssignmentToOuterVar() {
}
public AssignmentToOuterVar(String var, Evaluable expression) {
this.expression = expression;
this.var = var;
}
public Object[] _fieldsToList() {
return new Object[] { var, expression };
}
public Object get(VarContext ctx) {
var parent = ctx.parent();
assertNotNull("No outer variable context", parent);
Object o = expression.get(ctx);
parent.set(var, o);
return o;
}
public String toString() {
return "outer " + var + " <- " + expression;
}
}
static public class NewObject extends EvaluableBase {
public NewObject() {
}
public Class c;
public Evaluable[] args;
public NewObject(Class c) {
this.c = c;
}
public NewObject(Class c, Evaluable[] args) {
this.args = args;
this.c = c;
}
public Object get(VarContext ctx) {
try {
return preciseNuObject(c, evalArgs(args, ctx));
} catch (Throwable e) {
throw rethrowWithSrc(e);
}
}
public String toString() {
return "new " + formatFunctionCall(className(c), args);
}
}
static public class NewObject_LASClass extends NewObject {
public NewObject_LASClass() {
}
public ResolvableLASClass lasClass;
public NewObject_LASClass(ResolvableLASClass lasClass) {
this.lasClass = lasClass;
}
public NewObject_LASClass(ResolvableLASClass lasClass, Evaluable[] args) {
this.args = args;
this.lasClass = lasClass;
}
public void resolve() {
if (c == null)
c = lasClass.get();
}
public Object get(VarContext ctx) {
resolve();
return super.get(ctx);
}
public String toString() {
return "new " + formatFunctionCall(str(lasClass), args);
}
}
static public class NewObject_UnknownClass extends NewObject implements IFieldsToList {
public Evaluable classExpr;
public Evaluable[] args;
public NewObject_UnknownClass() {
}
public NewObject_UnknownClass(Evaluable classExpr, Evaluable[] args) {
this.args = args;
this.classExpr = classExpr;
}
public Object[] _fieldsToList() {
return new Object[] { classExpr, args };
}
public Object get(VarContext ctx) {
try {
Class c = (Class) (classExpr.get(ctx));
return preciseNuObject(c, evalArgs(args, ctx));
} catch (Throwable e) {
throw rethrowWithSrc(e);
}
}
public String toString() {
return "new " + formatFunctionCall(classExpr, args);
}
}
static public class CallFunction extends EvaluableBase implements IFieldsToList {
public FunctionDef f;
public Evaluable[] args;
public CallFunction() {
}
public CallFunction(FunctionDef f, Evaluable[] args) {
this.args = args;
this.f = f;
}
public Object[] _fieldsToList() {
return new Object[] { f, args };
}
public Object get(VarContext ctx) {
var evaledArgs = evalArgs(args, ctx);
if (ctx.exiting())
return null;
return f.call(ctx, evaledArgs);
}
public String toString() {
return formatFunctionCall(f.name, args);
}
}
static public class GetVar extends EvaluableBase implements IFieldsToList {
public String var;
public GetVar() {
}
public GetVar(String var) {
this.var = var;
}
public Object[] _fieldsToList() {
return new Object[] { var };
}
public Object get(VarContext ctx) {
return ctx.get(var);
}
public String toString() {
return var;
}
}
static public class GetFixedVar extends FixedVarBase {
public GetFixedVar() {
}
public GetFixedVar(LASScope scope, String var) {
this.var = var;
this.scope = scope;
}
public Object get(VarContext ctx) {
assertResolved();
try {
return ((FixedVarContext) ctx).get(varIdx);
} catch (ArrayIndexOutOfBoundsException e) {
assertResolved();
throw e;
}
}
public String toString() {
return var + " [" + varIdx + "]";
}
}
static public class Const extends EvaluableBase implements IFieldsToList {
public Object value;
public Const() {
}
public Const(Object value) {
this.value = value;
}
public Object[] _fieldsToList() {
return new Object[] { value };
}
public Object get(VarContext ctx) {
return value;
}
public String toString() {
return strOrClassName(value);
}
public LASValueDescriptor returnType() {
return new LASValueDescriptor.KnownValue(value);
}
public Object _serialize() {
boolean ok = isUnproblematicValue(value);
return ok ? this : toStringWithClass(value);
}
}
static public class GetStaticField extends EvaluableBase implements IFieldsToList {
public Field field;
public GetStaticField() {
}
public GetStaticField(Field field) {
this.field = field;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + field + ")";
}
public Object[] _fieldsToList() {
return new Object[] { field };
}
public Object get(VarContext ctx) {
try {
return field.get(null);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String _serialize() {
return str(field);
}
}
abstract static public class CallOnTarget extends EvaluableBase implements IFieldsToList {
public Evaluable target;
public CallOnTarget() {
}
public CallOnTarget(Evaluable target) {
this.target = target;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + target + ")";
}
public Object[] _fieldsToList() {
return new Object[] { target };
}
final public CallOnTarget setAllowNullReference(boolean allowNullReference) {
return allowNullReference(allowNullReference);
}
public CallOnTarget allowNullReference(boolean allowNullReference) {
this.allowNullReference = allowNullReference;
return this;
}
final public boolean getAllowNullReference() {
return allowNullReference();
}
public boolean allowNullReference() {
return allowNullReference;
}
public boolean allowNullReference = false;
public Object handleNullReference() {
if (allowNullReference)
return null;
else
throw new NullPointerException();
}
abstract public Object evalOnTarget(VarContext ctx, Object object);
public Object get(VarContext ctx) {
try {
Object object = target.get(ctx);
if (object == null)
return handleNullReference();
return evalOnTarget(ctx, object);
} catch (Throwable e) {
throw rethrowWithSrc(e);
}
}
}
static public class CallMethodOrGetField extends CallOnTarget {
public CallMethodOrGetField() {
}
public String name;
public CallMethodOrGetField(Evaluable target, String name) {
this.name = name;
this.target = target;
}
public Object evalOnTarget(VarContext ctx, Object object) {
try {
return preciseGetOrCallMethod(object, name);
} catch (Throwable e) {
throw rethrowWithSrc("Was getting " + name, e);
}
}
}
static public class GetField extends CallOnTarget {
public GetField() {
}
public String name;
public GetField(Evaluable target, String name) {
this.name = name;
this.target = target;
}
public Object evalOnTarget(VarContext ctx, Object object) {
try {
return _get(object, name);
} catch (Throwable e) {
throw rethrowWithSrc("Was getting " + name, e);
}
}
}
static public class GetVarContext extends EvaluableBase {
public Object get(VarContext ctx) {
return ctx;
}
}
static public class ThrowMethodNotFoundException extends EvaluableBase implements IFieldsToList {
public CallMethod instruction;
public ThrowMethodNotFoundException() {
}
public ThrowMethodNotFoundException(CallMethod instruction) {
this.instruction = instruction;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + instruction + ")";
}
public Object[] _fieldsToList() {
return new Object[] { instruction };
}
public Object get(VarContext ctx) {
throw fail("Method not found: " + instruction);
}
}
static public class ThrowNullPointerException extends EvaluableBase implements IFieldsToList {
public CallMethod instruction;
public ThrowNullPointerException() {
}
public ThrowNullPointerException(CallMethod instruction) {
this.instruction = instruction;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + instruction + ")";
}
public Object[] _fieldsToList() {
return new Object[] { instruction };
}
public Object get(VarContext ctx) {
throw fail("Null pointer exception: " + instruction);
}
}
static public class CallMethod extends CallOnTarget {
public CallMethod() {
}
public String methodName;
public Evaluable[] args;
public CallMethod(Evaluable target, String methodName, Evaluable[] args) {
this.args = args;
this.methodName = methodName;
this.target = target;
}
public Object evalOnTarget(VarContext ctx, Object object) {
return newPreciseCall(object, methodName, evalArgs(args, ctx));
}
public String toString() {
return target + "." + formatFunctionCall(methodName, args);
}
public Evaluable optimize() {
var targetType = target.returnType();
if (targetType != null && targetType.knownValue()) {
Object o = targetType.value();
if (o == null)
return allowNullReference ? _const(null) : new ThrowNullPointerException(this);
Class[] argTypes = new Class[l(args)];
for (int i = 0; i < l(args); i++) {
var type = args[i].returnType();
if (type == null || !type.javaClassIsExact())
return this;
argTypes[i] = type.javaClass();
}
List methods = findMethodsNamed_cached(o, methodName);
if (any(methods, m -> m.isVarArgs()))
return this;
var __4 = findMethod_withPrimitiveWidening_onTypes(o, methodName, argTypes);
var method = __4.a;
var widening = __4.b;
if (method == null)
return new ThrowMethodNotFoundException(this);
return new DirectMethodCallOnKnownTarget(widening, o instanceof Class ? null : o, method, args);
}
return this;
}
}
static public Object[] evalArgs(Evaluable[] args, VarContext ctx) {
return mapToArrayOrNull(args, arg -> arg.get(ctx));
}
static public class CallMethodOrGlobalFunction extends CallMethod {
public CallMethodOrGlobalFunction() {
}
public MethodOnObject globalFunction;
static final public Object methodNotFoundSentinel = new Object();
public CallMethodOrGlobalFunction(Evaluable target, String methodName, MethodOnObject globalFunction, Evaluable[] args) {
this.args = args;
this.globalFunction = globalFunction;
this.methodName = methodName;
this.target = target;
}
public String toString() {
return target + "." + formatFunctionCall(methodName + "+", args);
}
public Object evalOnTarget(VarContext ctx, Object o) {
Object[] realArgs = evalArgs(args, ctx);
Object result = newPreciseCall_sentinel(o, methodName, methodNotFoundSentinel, realArgs);
if (result != methodNotFoundSentinel)
return result;
return newPreciseCall(globalFunction.object, globalFunction.method, itemPlusArray(o, realArgs));
}
}
static public class CallMethodOrGetFieldOrGlobalFunction extends CallMethodOrGetField {
public CallMethodOrGetFieldOrGlobalFunction() {
}
public MethodOnObject globalFunction;
static final public Object notFoundSentinel = new Object();
public CallMethodOrGetFieldOrGlobalFunction(Evaluable target, String name, MethodOnObject globalFunction) {
this.globalFunction = globalFunction;
this.name = name;
this.target = target;
}
public String toString() {
return target + "." + name + "+";
}
public Object evalOnTarget(VarContext ctx, Object o) {
Object result = preciseGetOrCallMethod_sentinel(o, name, notFoundSentinel);
if (result != notFoundSentinel)
return result;
return newPreciseCall(globalFunction.object, globalFunction.method, o);
}
}
abstract static public class LambdaBase extends EvaluableBase implements IFieldsToList {
public Class intrface;
public LambdaBase() {
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + intrface + ")";
}
public Object[] _fieldsToList() {
return new Object[] { intrface };
}
transient public Method implementedMethod;
public LambdaBase(Class intrface) {
this.intrface = intrface;
implementedMethod = findSingleInterfaceMethodOrFail(intrface);
}
}
static public class LambdaMethodOnArgument extends LambdaBase {
public String methodName;
public Evaluable[] args;
public LambdaMethodOnArgument(Class intrface, String methodName, Evaluable[] args) {
super(intrface);
this.args = args;
this.methodName = methodName;
}
public Object get(VarContext ctx) {
return proxyFromInvocationHandler(intrface, (proxy, method, actualArgs) -> {
if (method.getDeclaringClass() == intrface)
return forwardCall(actualArgs[0], ctx);
else
return handleObjectMethodsInProxyInvocationHandler(this, implementedMethod, method, proxy, actualArgs);
});
}
public Object forwardCall(Object target, VarContext ctx) {
return call(target, methodName, evalArgs(args, ctx));
}
}
static public class LambdaDef extends EvaluableBase implements IFieldsToList {
public Class intrface;
public String[] args;
public Evaluable body;
public LambdaDef() {
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + intrface + ", " + args + ", " + body + ")";
}
public Object[] _fieldsToList() {
return new Object[] { intrface, args, body };
}
transient public Method implementedMethod;
public LambdaDef(Class intrface, String[] args, Evaluable body) {
this.body = body;
this.args = args;
this.intrface = intrface;
implementedMethod = findSingleInterfaceMethodOrFail(intrface);
if (implementedMethod.getParameterCount() != l(args))
throw fail("Bad parameter count for lambda: " + implementedMethod + " vs: " + joinWithComma(args));
}
public Object get(VarContext ctx) {
return proxyFromInvocationHandler(intrface, (proxy, method, actualArgs) -> {
ping();
if (method.getDeclaringClass() == intrface) {
var ctx2 = new FlexibleVarContext(ctx);
var argNames = args;
for (int i = 0; i < l(args); i++) ctx2.put(argNames[i], actualArgs[i]);
return body.get(ctx2);
} else
return handleObjectMethodsInProxyInvocationHandler(this, implementedMethod, method, proxy, actualArgs);
});
}
}
abstract static public class CurriedLambdaBase extends EvaluableBase implements IFieldsToList {
public Class intrface;
public Evaluable[] curriedArgs;
public CurriedLambdaBase() {
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + intrface + ", " + curriedArgs + ")";
}
public Object[] _fieldsToList() {
return new Object[] { intrface, curriedArgs };
}
transient public Method implementedMethod;
public CurriedLambdaBase(Class intrface, Evaluable[] curriedArgs) {
this.curriedArgs = curriedArgs;
this.intrface = intrface;
implementedMethod = findSingleInterfaceMethodOrFail(intrface);
}
public Object get(VarContext ctx) {
try {
Object[] curriedArguments = evalArgs(curriedArgs, ctx);
return proxyFromInvocationHandler(intrface, (proxy, method, actualArgs) -> {
try {
if (method.getDeclaringClass() == intrface)
return forwardCall(ctx, concatMethodArgs(curriedArguments, actualArgs));
else
return handleObjectMethodsInProxyInvocationHandler(this, implementedMethod, method, proxy, actualArgs);
} catch (Throwable e) {
throw rethrowWithSrc(e);
}
});
} catch (Throwable e) {
throw rethrowWithSrc(e);
}
}
abstract public Object forwardCall(VarContext ctx, Object[] args);
}
static public class CurriedMethodLambda extends CurriedLambdaBase {
public CurriedMethodLambda() {
}
public Object target;
public String targetMethod;
public CurriedMethodLambda(Class intrface, Object target, String targetMethod, Evaluable[] curriedArgs) {
super(intrface, curriedArgs);
this.targetMethod = targetMethod;
this.target = target;
}
public Object forwardCall(VarContext ctx, Object[] args) {
return call(target, targetMethod, args);
}
}
static public class CurriedScriptFunctionLambda extends CurriedLambdaBase {
public FunctionDef f;
public CurriedScriptFunctionLambda(Class intrface, FunctionDef f, Evaluable[] curriedArgs) {
super(intrface, curriedArgs);
this.f = f;
}
public Object forwardCall(VarContext ctx, Object[] args) {
return f.call(ctx, args);
}
}
static public class CurriedConstructorLambda extends CurriedLambdaBase {
public Constructor[] ctors;
public CurriedConstructorLambda(Class intrface, Constructor[] ctors, Evaluable[] curriedArgs) {
super(intrface, curriedArgs);
this.ctors = ctors;
}
public Object forwardCall(VarContext ctx, Object[] args) {
return preciseNuObject(ctors, args);
}
}
static public class DirectMethodCallOnKnownTarget extends EvaluableBase implements IFieldsToList {
public boolean widening = false;
public Object target;
public Method method;
public Evaluable[] args;
public DirectMethodCallOnKnownTarget() {
}
public DirectMethodCallOnKnownTarget(boolean widening, Object target, Method method, Evaluable[] args) {
this.args = args;
this.method = method;
this.target = target;
this.widening = widening;
}
public Object[] _fieldsToList() {
return new Object[] { widening, target, method, args };
}
public Object get(VarContext ctx) {
var evaluatedArgs = evalArgs(args, ctx);
return widening ? invokeMethodWithWidening(method, target, evaluatedArgs) : invokeMethod(method, target, evaluatedArgs);
}
public String toString() {
return (target == null ? "" : target + ".") + formatFunctionCall(str(method), args);
}
public LASValueDescriptor returnType() {
return LASValueDescriptor.fromClass(method.getReturnType());
}
}
static public class While extends EvaluableBase implements IFieldsToList {
public Evaluable condition;
public Evaluable body;
public While() {
}
public While(Evaluable condition, Evaluable body) {
this.body = body;
this.condition = condition;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + condition + ", " + body + ")";
}
public Object[] _fieldsToList() {
return new Object[] { condition, body };
}
public Object get(VarContext ctx) {
while (!ctx.exiting() && (Boolean) condition.get(ctx)) {
body.get(ctx);
}
return null;
}
}
abstract static public class ForEachBase extends EvaluableBase implements IFieldsToList {
public Evaluable collection;
public Evaluable body;
public ForEachBase() {
}
public ForEachBase(Evaluable collection, Evaluable body) {
this.body = body;
this.collection = collection;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + collection + ", " + body + ")";
}
public Object[] _fieldsToList() {
return new Object[] { collection, body };
}
public Object get(VarContext ctx) {
var coll = collection.get(ctx);
Iterator iterator;
List out;
try {
if (coll == null)
out = new ArrayList();
else if (coll.getClass().isArray()) {
if (coll instanceof Object[]) {
var array = (Object[]) coll;
out = emptyList(array.length);
for (var element : array) {
if (ctx.exiting())
return null;
processElement(ctx, out, element);
}
} else if (coll instanceof byte[]) {
var array = (byte[]) coll;
out = emptyList(array.length);
for (var element : array) {
if (ctx.exiting())
return null;
processElement(ctx, out, element);
}
} else if (coll instanceof short[]) {
var array = (short[]) coll;
out = emptyList(array.length);
for (var element : array) {
if (ctx.exiting())
return null;
processElement(ctx, out, element);
}
} else if (coll instanceof double[]) {
var array = (double[]) coll;
out = emptyList(array.length);
for (var element : array) {
if (ctx.exiting())
return null;
processElement(ctx, out, element);
}
} else if (coll instanceof float[]) {
var array = (float[]) coll;
out = emptyList(array.length);
for (var element : array) {
if (ctx.exiting())
return null;
processElement(ctx, out, element);
}
} else if (coll instanceof int[]) {
var array = (int[]) coll;
out = emptyList(array.length);
for (var element : array) {
if (ctx.exiting())
return null;
processElement(ctx, out, element);
}
} else if (coll instanceof long[]) {
var array = (long[]) coll;
out = emptyList(array.length);
for (var element : array) {
if (ctx.exiting())
return null;
processElement(ctx, out, element);
}
} else if (coll instanceof char[]) {
var array = (char[]) coll;
out = emptyList(array.length);
for (var element : array) {
if (ctx.exiting())
return null;
processElement(ctx, out, element);
}
} else if (coll instanceof boolean[]) {
var array = (boolean[]) coll;
out = emptyList(array.length);
for (var element : array) {
if (ctx.exiting())
return null;
processElement(ctx, out, element);
}
} else
throw fail("todo for each with: " + coll);
} else if (coll instanceof Iterable) {
out = emptyList((Iterable) coll);
iterator = ((Iterable) coll).iterator();
try {
while (iterator.hasNext()) {
if (ctx.exiting())
return null;
var element = iterator.next();
processElement(ctx, out, element);
}
} finally {
if (iterator instanceof AutoCloseable) {
try {
((AutoCloseable) iterator).close();
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
} else
throw fail("Not iterable: " + className(coll));
} finally {
loopDone(ctx);
}
return out;
}
abstract public void processElement(VarContext ctx, List out, Object o);
abstract public void loopDone(VarContext ctx);
}
static public class ForEach extends ForEachBase {
public ForEach() {
}
public String var;
public ForEach(Evaluable collection, String var, Evaluable body) {
this.body = body;
this.var = var;
this.collection = collection;
}
public void processElement(VarContext ctx, List out, Object o) {
ctx.set(var, o);
out.add(body.get(ctx));
}
public void loopDone(VarContext ctx) {
ctx.unset(var);
}
}
static public class ForIterator extends EvaluableBase implements IFieldsToList {
static final public String _fieldOrder = "iterable var body";
public Evaluable iterable;
public String var;
public Evaluable body;
public ForIterator() {
}
public ForIterator(Evaluable iterable, String var, Evaluable body) {
this.body = body;
this.var = var;
this.iterable = iterable;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + iterable + ", " + var + ", " + body + ")";
}
public boolean equals(Object o) {
if (!(o instanceof ForIterator))
return false;
ForIterator __5 = (ForIterator) o;
return eq(iterable, __5.iterable) && eq(var, __5.var) && eq(body, __5.body);
}
public int hashCode() {
int h = -214906825;
h = boostHashCombine(h, _hashCode(iterable));
h = boostHashCombine(h, _hashCode(var));
h = boostHashCombine(h, _hashCode(body));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { iterable, var, body };
}
public Object get(VarContext ctx) {
VarContext subContext = new FlexibleVarContext(ctx);
var iterable = this.iterable.get(ctx);
Iterator iterator = iterator_gen(iterable);
return new MapI(value -> {
subContext.set(var, value);
return body.get(subContext);
}, iterator);
}
}
static public class ForNested extends EvaluableBase implements IFieldsToList {
static final public String _fieldOrder = "iterable var body";
public Evaluable iterable;
public String var;
public Evaluable body;
public ForNested() {
}
public ForNested(Evaluable iterable, String var, Evaluable body) {
this.body = body;
this.var = var;
this.iterable = iterable;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + iterable + ", " + var + ", " + body + ")";
}
public boolean equals(Object o) {
if (!(o instanceof ForNested))
return false;
ForNested __6 = (ForNested) o;
return eq(iterable, __6.iterable) && eq(var, __6.var) && eq(body, __6.body);
}
public int hashCode() {
int h = -1363247360;
h = boostHashCombine(h, _hashCode(iterable));
h = boostHashCombine(h, _hashCode(var));
h = boostHashCombine(h, _hashCode(body));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { iterable, var, body };
}
public Object get(VarContext ctx) {
VarContext subContext = new FlexibleVarContext(ctx);
var iterable = this.iterable.get(ctx);
Iterator iterator = iterator_gen(iterable);
return nestedIterator(iterator, value -> {
subContext.set(var, value);
return iterator_gen(body.get(subContext));
});
}
}
static public class ForPairs extends ForEachBase {
public ForPairs() {
}
public String varA, varB;
public ForPairs(Evaluable collection, Evaluable body, String varA, String varB) {
this.varB = varB;
this.varA = varA;
this.body = body;
this.collection = collection;
}
public void processElement(VarContext ctx, List out, Object o) {
Pair p = (Pair) o;
ctx.set(varA, p.a);
ctx.set(varB, p.b);
out.add(body.get(ctx));
}
public void loopDone(VarContext ctx) {
ctx.unset(varA);
ctx.unset(varB);
}
}
static public class ForKeyValue extends EvaluableBase implements IFieldsToList {
public Evaluable map;
public Evaluable body;
public String varA;
public String varB;
public ForKeyValue() {
}
public ForKeyValue(Evaluable map, Evaluable body, String varA, String varB) {
this.varB = varB;
this.varA = varA;
this.body = body;
this.map = map;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + map + ", " + body + ", " + varA + ", " + varB + ")";
}
public Object[] _fieldsToList() {
return new Object[] { map, body, varA, varB };
}
public Object get(VarContext ctx) {
Map, ?> theMap = (Map) map.get(ctx);
List out;
try {
if (theMap != null) {
out = emptyList(theMap.size());
for (var entry : theMap.entrySet()) {
if (ctx.exiting())
return null;
ctx.set(varA, entry.getKey());
ctx.set(varB, entry.getValue());
out.add(body.get(ctx));
}
} else
out = new ArrayList();
} finally {
ctx.unset(varA);
ctx.unset(varB);
}
return out;
}
}
static public class ForIntTo extends EvaluableBase implements IFieldsToList {
public Evaluable endValue;
public String var;
public Evaluable body;
public ForIntTo() {
}
public ForIntTo(Evaluable endValue, String var, Evaluable body) {
this.body = body;
this.var = var;
this.endValue = endValue;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + endValue + ", " + var + ", " + body + ")";
}
public Object[] _fieldsToList() {
return new Object[] { endValue, var, body };
}
public Evaluable optimize() {
if (!returnValueNeeded)
body = body.optimizeForReturnValueNotNeeded();
return this;
}
public Object get(VarContext ctx) {
int n = (Integer) endValue.get(ctx), i = 0;
List out = returnValueNeeded ? new ArrayList() : null;
try {
ctx.put(var, i);
while (i < n) {
if (ctx.exiting())
return null;
Object o = body.get(ctx);
{
if (out != null)
out.add(o);
}
ctx.set(var, i = (Integer) ctx.get(var) + 1);
}
} finally {
ctx.unset(var);
}
return out;
}
}
static public class ForIndex extends EvaluableBase {
public ForIndex() {
}
public Evaluable collection, body;
public String varIndex, varElement;
public ForIndex(Evaluable collection, Evaluable body, String varIndex, String varElement) {
this.varElement = varElement;
this.varIndex = varIndex;
this.body = body;
this.collection = collection;
}
public Object get(VarContext ctx) {
return new ForIndex_instance(collection, body, varIndex, varElement).get(ctx);
}
}
static public class ForIndex_instance extends ForEachBase {
public String varIndex, varElement;
public int index;
public ForIndex_instance(Evaluable collection, Evaluable body, String varIndex, String varElement) {
this.varElement = varElement;
this.varIndex = varIndex;
this.body = body;
this.collection = collection;
}
public void processElement(VarContext ctx, List out, Object o) {
ctx.set(varIndex, index++);
ctx.set(varElement, o);
out.add(body.get(ctx));
}
public void loopDone(VarContext ctx) {
ctx.unset(varIndex);
ctx.unset(varElement);
}
}
static public class IfThen extends EvaluableBase implements IFieldsToList {
public Evaluable condition;
public Evaluable body;
public Evaluable elseBranch;
public IfThen() {
}
public IfThen(Evaluable condition, Evaluable body, Evaluable elseBranch) {
this.elseBranch = elseBranch;
this.body = body;
this.condition = condition;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + condition + ", " + body + ", " + elseBranch + ")";
}
public Object[] _fieldsToList() {
return new Object[] { condition, body, elseBranch };
}
public IfThen(Evaluable condition, Evaluable body) {
this.condition = condition;
this.body = body;
}
public Object get(VarContext ctx) {
if ((Boolean) condition.get(ctx))
return body.get(ctx);
else if (elseBranch != null)
return elseBranch.get(ctx);
else
return null;
}
}
static public class ReturnFromScript extends EvaluableBase implements IFieldsToList {
public Script script;
public Evaluable value;
public ReturnFromScript() {
}
public ReturnFromScript(Script script, Evaluable value) {
this.value = value;
this.script = script;
}
public Object[] _fieldsToList() {
return new Object[] { script, value };
}
public Object get(VarContext ctx) {
Object result = value.get(ctx);
ctx.exitFromScript(script);
ctx.returnValue(result);
return null;
}
public String toString() {
return formatFunctionCall("ReturnFromScript", script, value);
}
}
static public class Continue extends EvaluableBase implements IFieldsToList {
public Script loopBody;
public Continue() {
}
public Continue(Script loopBody) {
this.loopBody = loopBody;
}
public Object[] _fieldsToList() {
return new Object[] { loopBody };
}
public Object get(VarContext ctx) {
ctx.exitFromScript(loopBody);
ctx.returnValue(null);
return null;
}
public String toString() {
return formatFunctionCall("Continue", loopBody);
}
}
static public class RepeatN extends EvaluableBase implements IFieldsToList {
public Evaluable n;
public Evaluable body;
public RepeatN() {
}
public RepeatN(Evaluable n, Evaluable body) {
this.body = body;
this.n = n;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + n + ", " + body + ")";
}
public Object[] _fieldsToList() {
return new Object[] { n, body };
}
public Object get(VarContext ctx) {
long count = ((Number) n.get(ctx)).longValue();
for (int _repeat_0 = 0; _repeat_0 < count; _repeat_0++) {
if (ctx.exiting())
return null;
body.get(ctx);
}
return null;
}
}
static public class BoolAnd extends EvaluableBase implements IFieldsToList {
public Evaluable a;
public Evaluable b;
public BoolAnd() {
}
public BoolAnd(Evaluable a, Evaluable b) {
this.b = b;
this.a = a;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + a + ", " + b + ")";
}
public boolean equals(Object o) {
if (!(o instanceof BoolAnd))
return false;
BoolAnd __7 = (BoolAnd) o;
return eq(a, __7.a) && eq(b, __7.b);
}
public int hashCode() {
int h = 1729330797;
h = boostHashCombine(h, _hashCode(a));
h = boostHashCombine(h, _hashCode(b));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { a, b };
}
public Object get(VarContext ctx) {
if (!((Boolean) a.get(ctx)))
return false;
return b.get(ctx);
}
}
static public class BoolOr extends EvaluableBase implements IFieldsToList {
public Evaluable a;
public Evaluable b;
public BoolOr() {
}
public BoolOr(Evaluable a, Evaluable b) {
this.b = b;
this.a = a;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + a + ", " + b + ")";
}
public boolean equals(Object o) {
if (!(o instanceof BoolOr))
return false;
BoolOr __8 = (BoolOr) o;
return eq(a, __8.a) && eq(b, __8.b);
}
public int hashCode() {
int h = 1995447949;
h = boostHashCombine(h, _hashCode(a));
h = boostHashCombine(h, _hashCode(b));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { a, b };
}
public Object get(VarContext ctx) {
if (((Boolean) a.get(ctx)))
return true;
return b.get(ctx);
}
}
static public class TempBlock extends EvaluableBase implements IFieldsToList {
public Evaluable tempExpr;
public Evaluable body;
public TempBlock() {
}
public TempBlock(Evaluable tempExpr, Evaluable body) {
this.body = body;
this.tempExpr = tempExpr;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + tempExpr + ", " + body + ")";
}
public Object[] _fieldsToList() {
return new Object[] { tempExpr, body };
}
public Object get(VarContext ctx) {
AutoCloseable __2 = (AutoCloseable) (tempExpr.get(ctx));
try {
return body.get(ctx);
} finally {
_close(__2);
}
}
}
static public class WillReturn extends EvaluableBase implements IFieldsToList {
public Evaluable exp;
public Evaluable body;
public WillReturn() {
}
public WillReturn(Evaluable exp, Evaluable body) {
this.body = body;
this.exp = exp;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + exp + ", " + body + ")";
}
public Object[] _fieldsToList() {
return new Object[] { exp, body };
}
public Object get(VarContext ctx) {
body.get(ctx);
return exp.get(ctx);
}
}
static public class ClassDef extends EvaluableBase implements IFieldsToList {
public ResolvableLASClass lasClass;
public ClassDef() {
}
public ClassDef(ResolvableLASClass lasClass) {
this.lasClass = lasClass;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + lasClass + ")";
}
public boolean equals(Object o) {
if (!(o instanceof ClassDef))
return false;
ClassDef __9 = (ClassDef) o;
return eq(lasClass, __9.lasClass);
}
public int hashCode() {
int h = 757052301;
h = boostHashCombine(h, _hashCode(lasClass));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { lasClass };
}
public Object get(VarContext ctx) {
return lasClass.get();
}
}
static public class SetField extends EvaluableBase implements IFieldsToList {
public Evaluable target;
public String name;
public Evaluable expr;
public SetField() {
}
public SetField(Evaluable target, String name, Evaluable expr) {
this.expr = expr;
this.name = name;
this.target = target;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + target + ", " + name + ", " + expr + ")";
}
public Object[] _fieldsToList() {
return new Object[] { target, name, expr };
}
final public SetField setAllowNullReference(boolean allowNullReference) {
return allowNullReference(allowNullReference);
}
public SetField allowNullReference(boolean allowNullReference) {
this.allowNullReference = allowNullReference;
return this;
}
final public boolean getAllowNullReference() {
return allowNullReference();
}
public boolean allowNullReference() {
return allowNullReference;
}
public boolean allowNullReference = false;
public Object handleNullReference() {
if (allowNullReference)
return null;
else
throw new NullPointerException();
}
public Object get(VarContext ctx) {
try {
Object value = expr.get(ctx);
Object object = target.get(ctx);
if (object == null)
handleNullReference();
else
set(object, name, value);
return value;
} catch (Throwable e) {
throw rethrowWithSrc(e);
}
}
}
static public class SetStaticField extends EvaluableBase implements IFieldsToList {
public Field field;
public Evaluable expr;
public SetStaticField() {
}
public SetStaticField(Field field, Evaluable expr) {
this.expr = expr;
this.field = field;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + field + ", " + expr + ")";
}
public Object[] _fieldsToList() {
return new Object[] { field, expr };
}
public Object get(VarContext ctx) {
try {
Object value = expr.get(ctx);
field.set(null, value);
return value;
} catch (Throwable e) {
throw rethrowWithSrc(e);
}
}
}
static public class Throw extends EvaluableBase implements IFieldsToList {
public Evaluable expr;
public Throw() {
}
public Throw(Evaluable expr) {
this.expr = expr;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + expr + ")";
}
public Object[] _fieldsToList() {
return new Object[] { expr };
}
public Object get(VarContext ctx) {
throw asRuntimeException((Throwable) expr.get(ctx));
}
}
static public class TryCatch extends EvaluableBase implements IFieldsToList {
public Evaluable body;
public String var;
public Evaluable catchBlock;
public TryCatch() {
}
public TryCatch(Evaluable body, String var, Evaluable catchBlock) {
this.catchBlock = catchBlock;
this.var = var;
this.body = body;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + body + ", " + var + ", " + catchBlock + ")";
}
public Object[] _fieldsToList() {
return new Object[] { body, var, catchBlock };
}
public Object get(VarContext ctx) {
try {
return body.get(ctx);
} catch (Throwable e) {
var addVar = var == null ? null : ctx.tempPut(var, e);
AutoCloseable __3 = addVar;
try {
return catchBlock.get(ctx);
} finally {
_close(__3);
}
}
}
}
static public class TryFinally extends EvaluableBase implements IFieldsToList {
public Evaluable body;
public Evaluable finallyBlock;
public TryFinally() {
}
public TryFinally(Evaluable body, Evaluable finallyBlock) {
this.finallyBlock = finallyBlock;
this.body = body;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + body + ", " + finallyBlock + ")";
}
public Object[] _fieldsToList() {
return new Object[] { body, finallyBlock };
}
public Object get(VarContext ctx) {
try {
return body.get(ctx);
} finally {
finallyBlock.get(ctx);
}
}
}
static public structure_Data structureDataForLAS() {
structure_Data d = new structure_Data();
d.skipDefaultValues(true);
d.shouldIncludeField = field -> {
String c = shortClassName(field.getDeclaringClass());
String f = field.getName();
boolean shouldInclude = !(eq(c, "HasTokenRangeWithSrc") && eq(f, "src"));
return shouldInclude;
};
return d;
}
static public boolean isUnproblematicValue(Object o) {
return o == null || o instanceof Number || o instanceof String || o instanceof Boolean || o instanceof Class;
}
static public String scriptStruct(Object o) {
String s = struct(o, structureDataForLAS());
List tok = structTok(s);
String prefix = shortName(GazelleV_LeftArrowScript.class) + "$";
for (int i = 1; i < l(tok); i += 2) tok.set(i, replacePrefix(prefix, "$", tok.get(i)));
return join(tok);
}
static public String indentedScriptStruct(Object o) {
return indentStructureString(scriptStruct(o));
}
static public Evaluable _const(Object o) {
return new Const(o);
}
static public class Then extends CallOnTarget {
public CallOnTarget call1, call2;
public Then(CallOnTarget call1, CallOnTarget call2) {
this.call2 = call2;
this.call1 = call1;
target = call1.target;
call1.target = null;
}
public Object evalOnTarget(VarContext ctx, Object object) {
call1.evalOnTarget(ctx, object);
return call2.evalOnTarget(ctx, object);
}
}
}
static public class LASValueDescriptor {
public LASValueDescriptor() {
}
public boolean knownValue() {
return false;
}
public Object value() {
return null;
}
public Class javaClass() {
return null;
}
public boolean javaClassIsExact() {
return false;
}
public boolean canBeNull() {
return true;
}
public boolean canFail() {
return false;
}
public boolean willFail() {
return false;
}
static public class Exact extends LASValueDescriptor implements IFieldsToList {
public Class c;
public boolean canBeNull = false;
public Exact() {
}
public Exact(Class c, boolean canBeNull) {
this.canBeNull = canBeNull;
this.c = c;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + c + ", " + canBeNull + ")";
}
public boolean equals(Object o) {
if (!(o instanceof Exact))
return false;
Exact __1 = (Exact) o;
return eq(c, __1.c) && eq(canBeNull, __1.canBeNull);
}
public int hashCode() {
int h = 67394271;
h = boostHashCombine(h, _hashCode(c));
h = boostHashCombine(h, _hashCode(canBeNull));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { c, canBeNull };
}
public Class javaClass() {
return c;
}
public boolean javaClassIsExact() {
return true;
}
public boolean canBeNull() {
return canBeNull;
}
}
static public class NonExact extends LASValueDescriptor implements IFieldsToList {
public Class c;
public boolean canBeNull = false;
public NonExact() {
}
public NonExact(Class c, boolean canBeNull) {
this.canBeNull = canBeNull;
this.c = c;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + c + ", " + canBeNull + ")";
}
public boolean equals(Object o) {
if (!(o instanceof NonExact))
return false;
NonExact __2 = (NonExact) o;
return eq(c, __2.c) && eq(canBeNull, __2.canBeNull);
}
public int hashCode() {
int h = 1445514322;
h = boostHashCombine(h, _hashCode(c));
h = boostHashCombine(h, _hashCode(canBeNull));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { c, canBeNull };
}
public Class javaClass() {
return c;
}
public boolean javaClassIsExact() {
return false;
}
public boolean canBeNull() {
return canBeNull;
}
}
static public LASValueDescriptor nonExactCanBeNull(Type c) {
return new NonExact(typeToClass(c), true);
}
static public class KnownValue extends LASValueDescriptor implements IFieldsToList {
public Object value;
public KnownValue() {
}
public KnownValue(Object value) {
this.value = value;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + value + ")";
}
public boolean equals(Object o) {
if (!(o instanceof KnownValue))
return false;
KnownValue __3 = (KnownValue) o;
return eq(value, __3.value);
}
public int hashCode() {
int h = -1456305138;
h = boostHashCombine(h, _hashCode(value));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { value };
}
public boolean knownValue() {
return true;
}
public Object value() {
return value;
}
public Class javaClass() {
return value == null ? null : value.getClass();
}
public boolean javaClassIsExact() {
return value != null;
}
public boolean canBeNull() {
return value == null;
}
}
static public class WillFail extends LASValueDescriptor {
public boolean canFail() {
return true;
}
public boolean willFail() {
return true;
}
}
static public LASValueDescriptor fromClass(Class c) {
return new NonExact(c, true);
}
}
static public class PingSourceCancelledException extends RuntimeException implements IFieldsToList {
public PingSource pingSource;
public PingSourceCancelledException() {
}
public PingSourceCancelledException(PingSource pingSource) {
this.pingSource = pingSource;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + pingSource + ")";
}
public Object[] _fieldsToList() {
return new Object[] { pingSource };
}
}
static public class TokenRangeWithSrc extends TokenRange {
public List tok;
final public TokenRangeWithSrc setSourceInfo(Object sourceInfo) {
return sourceInfo(sourceInfo);
}
public TokenRangeWithSrc sourceInfo(Object sourceInfo) {
this.sourceInfo = sourceInfo;
return this;
}
final public Object getSourceInfo() {
return sourceInfo();
}
public Object sourceInfo() {
return sourceInfo;
}
public Object sourceInfo;
public TokenRangeWithSrc() {
}
public TokenRangeWithSrc(List tok, int start) {
this.start = start;
end = start;
}
public TokenRangeWithSrc(List tok, int start, int end) {
this.end = end;
this.start = start;
}
public TokenRangeWithSrc(ListAndIndex startPtr, ListAndIndex endPtr) {
assertNotNull("startPtr", startPtr);
assertNotNull("endPtr", endPtr);
assertSame(tok = startPtr.list(), endPtr.list());
start = startPtr.idx();
end = endPtr.idx();
}
public ListAndIndex startPtr() {
return new ListAndIndex(tok, start);
}
public ListAndIndex endPtr() {
return new ListAndIndex(tok, end);
}
public LineAndColumn startLineAndCol() {
return tokenToLineAndColumn(startPtr());
}
public LineAndColumn endLineAndCol() {
return tokenToLineAndColumn(endPtr());
}
public String text() {
return joinSubList(tok, start, end);
}
public String renderRange() {
return renderLineAndColumnRange(startLineAndCol(), endLineAndCol());
}
public String toString() {
return spaceCombine(sourceInfo(), renderRange());
}
public String fullSourceText() {
return join(tok);
}
}
static public class LASScope {
final public LASScope setUseFixedVars(boolean useFixedVars) {
return useFixedVars(useFixedVars);
}
public LASScope useFixedVars(boolean useFixedVars) {
this.useFixedVars = useFixedVars;
return this;
}
final public boolean getUseFixedVars() {
return useFixedVars();
}
public boolean useFixedVars() {
return useFixedVars;
}
public boolean useFixedVars = false;
final public Map getDeclaredVars() {
return declaredVars();
}
public Map declaredVars() {
return declaredVars;
}
public Map declaredVars = new HashMap();
final public LASScope setParentScope(LASScope parentScope) {
return parentScope(parentScope);
}
public LASScope parentScope(LASScope parentScope) {
this.parentScope = parentScope;
return this;
}
final public LASScope getParentScope() {
return parentScope();
}
public LASScope parentScope() {
return parentScope;
}
public LASScope parentScope;
final public LASScope setParentIsDetached(boolean parentIsDetached) {
return parentIsDetached(parentIsDetached);
}
public LASScope parentIsDetached(boolean parentIsDetached) {
this.parentIsDetached = parentIsDetached;
return this;
}
final public boolean getParentIsDetached() {
return parentIsDetached();
}
public boolean parentIsDetached() {
return parentIsDetached;
}
public boolean parentIsDetached = false;
public String[] names;
public LASScope() {
}
public LASScope(LASScope parentScope) {
this.parentScope = parentScope;
}
public boolean resolved() {
return names != null;
}
public void addDeclaredVar(String name, LASValueDescriptor type) {
if (resolved())
throw fail("Can't add variables to resolved scope");
declaredVars.put(name, type);
}
public int resolveVar(String name) {
resolve();
int idx = indexOfInSortedArray(names, name);
if (idx < 0)
throw fail("Variable not found in scope: " + name);
return idx;
}
public void resolve() {
if (names != null)
return;
names = empty(declaredVars) ? null : toStringArray(sortedKeys(declaredVars));
}
}
static public class InMemoryClassLoader extends ClassLoader {
final public InMemoryClassLoader setRememberClassBytes(boolean rememberClassBytes) {
return rememberClassBytes(rememberClassBytes);
}
public InMemoryClassLoader rememberClassBytes(boolean rememberClassBytes) {
this.rememberClassBytes = rememberClassBytes;
return this;
}
final public boolean getRememberClassBytes() {
return rememberClassBytes();
}
public boolean rememberClassBytes() {
return rememberClassBytes;
}
transient public boolean rememberClassBytes = false;
transient public Map classBytes = syncMap();
public InMemoryClassLoader(ClassLoader parent) {
super(parent);
}
public Class> defineAClass(String name, byte[] bytes) {
Class c = defineClass(name, bytes, 0, bytes.length);
if (rememberClassBytes)
classBytes.put(c, bytes);
return c;
}
public byte[] getClassBytes(Class c) {
return classBytes.get(c);
}
}
static public class ClassNameResolver {
final public ClassNameResolver setByteCodePath(File byteCodePath) {
return byteCodePath(byteCodePath);
}
public ClassNameResolver byteCodePath(File byteCodePath) {
this.byteCodePath = byteCodePath;
return this;
}
final public File getByteCodePath() {
return byteCodePath();
}
public File byteCodePath() {
return byteCodePath;
}
public File byteCodePath = byteCodePathForClass(getClass());
public List importedPackages = itemPlusList("java.lang", endingWith_dropSuffix(standardImports(), ".*"));
public Set allFullyQualifiedClassNames_cache;
public Set allFullyQualifiedClassNames() {
if (allFullyQualifiedClassNames_cache == null)
allFullyQualifiedClassNames_cache = allFullyQualifiedClassNames_load();
return allFullyQualifiedClassNames_cache;
}
public Set allFullyQualifiedClassNames_load() {
Set set = new HashSet();
assertNotNull(byteCodePath);
set.addAll(classNamesInJarOrDir(byteCodePath));
printVars("ClassNameResolver", "byteCodePath", byteCodePath, "classesFound", l(set));
set.addAll(classNamesInLoadedJigsawModules());
return set;
}
public ClassNameResolver init() {
allFullyQualifiedClassNames();
return this;
}
public String findClass(String name) {
for (String pkg : importedPackages) {
String fullName = pkg + "." + name;
if (allFullyQualifiedClassNames().contains(fullName))
return fullName;
}
return null;
}
public void printMe() {
printVars("ClassNameResolver", "byteCodePath", byteCodePath);
print("importedPackages", importedPackages);
}
}
static public class ThreadPool implements AutoCloseable {
public int max = numberOfCores();
public List all = new ArrayList();
public Set used = new HashSet();
public Set free = new HashSet();
public boolean verbose, retired;
public class InternalPingSource extends PingSource {
}
public InternalPingSource internalPingSource = new InternalPingSource();
public MultiSleeper sleeper = new MultiSleeper();
public ThreadPool() {
}
public ThreadPool(int max) {
this.max = max;
}
synchronized public int maxSize() {
return max;
}
synchronized public int total() {
return l(used) + l(free);
}
transient public Set onCustomerMustWaitAlert;
public ThreadPool onCustomerMustWaitAlert(Runnable r) {
onCustomerMustWaitAlert = createOrAddToSyncLinkedHashSet(onCustomerMustWaitAlert, r);
return this;
}
public ThreadPool removeCustomerMustWaitAlertListener(Runnable r) {
main.remove(onCustomerMustWaitAlert, r);
return this;
}
public void customerMustWaitAlert() {
if (onCustomerMustWaitAlert != null)
for (var listener : onCustomerMustWaitAlert) pcallF_typed(listener);
}
public void fireCustomerMustWaitAlert() {
vmBus_send("customerMustWaitAlert", this, currentThread());
customerMustWaitAlert();
}
public PooledThread acquireThreadOrQueue(Runnable action) {
if (action == null)
return null;
PooledThread t;
synchronized (this) {
if (_hasFreeAfterCreating()) {
t = _firstFreeThread();
markUsed(t);
} else
t = _anyThread();
}
t.addWork(action);
return t;
}
public boolean _hasFreeAfterCreating() {
checkNotRetired();
if (nempty(free))
return true;
if (total() < max) {
PooledThread t = newThread();
all.add(t);
free.add(t);
return true;
}
return false;
}
public PooledThread acquireThreadOrWait(Runnable action) {
try {
if (action == null)
return null;
PooledThread t;
while (true) {
synchronized (this) {
if (_hasFreeAfterCreating()) {
t = _firstFreeThread();
break;
} else
_waitWaitWait();
}
}
t.addWork(action);
return t;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public PooledThread _firstFreeThread() {
return first(free);
}
public PooledThread _anyThread() {
return random(used);
}
public class PooledThread extends Thread {
public PooledThread(String name) {
super(name);
}
public AppendableChain q;
synchronized public Runnable _grabWorkOrSleep() {
try {
Runnable r = first(q);
if (r == null) {
markFree(this);
if (verbose)
print("Thread sleeps");
synchronized (this) {
wait();
}
if (verbose)
print("Thread woke up");
return null;
}
q = popFirst(q);
return r;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void run() {
try {
pingSource_tl().set(internalPingSource);
while (!retired()) {
ping();
Runnable r = _grabWorkOrSleep();
if (verbose)
print(this + " work: " + r);
if (r != null)
try {
if (verbose)
print(this + " running: " + r);
r.run();
pingSource_tl().set(internalPingSource);
if (verbose)
print(this + " done");
} catch (Throwable e) {
pingSource_tl().set(internalPingSource);
if (verbose)
print(this + " error");
printStackTrace(e);
} finally {
pingSource_tl().set(internalPingSource);
if (verbose)
print("ThreadPool finally");
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
synchronized public boolean isEmpty() {
return empty(q);
}
public void addWork(Runnable r) {
if (verbose)
print("Added work to " + this + ": " + r);
synchronized (this) {
q = chainPlus(q, r);
notifyAll();
}
}
}
public PooledThread newThread() {
PooledThread t = new PooledThread("Thread Pool Inhabitant " + n2(total() + 1));
t.start();
return t;
}
synchronized public void markFree(PooledThread t) {
used.remove(t);
free.add(t);
notifyAll();
}
synchronized public void markUsed(PooledThread t) {
free.remove(t);
used.add(t);
}
synchronized public String toString() {
return retired() ? "Retired ThreadPool" : "ThreadPool " + roundBracket(commaCombine(n2(used) + " used out of " + n2(total()), max <= total() ? null : "could grow to " + n2(max)));
}
synchronized public boolean retired() {
return retired;
}
synchronized public void retire() {
if (verbose)
print("ThreadPool Retiring");
retired = true;
for (var thread : free) syncNotifyAll(thread);
}
public void checkNotRetired() {
if (retired())
throw fail("retired");
}
synchronized public void close() {
try {
retire();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void _waitWaitWait() {
try {
do {
fireCustomerMustWaitAlert();
wait();
checkNotRetired();
} while (empty(free));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void dO(String text, Runnable r) {
if (r == null)
return;
new PingSource(this, text).dO(r);
}
public ISleeper_v2 sleeper() {
return sleeper;
}
}
static final public class ParameterizedTypeImpl implements ParameterizedType {
public ParameterizedTypeImpl() {
}
public Type ownerType;
public Type rawType;
public Type[] typeArguments;
public ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) {
this.typeArguments = typeArguments;
this.rawType = rawType;
this.ownerType = ownerType;
}
public Type[] getActualTypeArguments() {
return typeArguments;
}
public Type getRawType() {
return rawType;
}
public Type getOwnerType() {
return ownerType;
}
@Override
public boolean equals(Object other) {
if (other instanceof ParameterizedType)
return eq(ownerType, ((ParameterizedType) other).getOwnerType()) && eq(rawType, ((ParameterizedType) other).getRawType()) && eq(asList(typeArguments), asList(((ParameterizedType) other).getActualTypeArguments()));
return false;
}
@Override
public int hashCode() {
return Arrays.hashCode(typeArguments) ^ rawType.hashCode() ^ _hashCode(ownerType);
}
@Override
public String toString() {
int length = typeArguments.length;
if (length == 0)
return typeToString(rawType);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(typeToString(rawType)).append("<").append(typeToString(typeArguments[0]));
for (int i = 1; i < length; i++) {
stringBuilder.append(", ").append(typeToString(typeArguments[i]));
}
return stringBuilder.append(">").toString();
}
static public String typeToString(Type type) {
return type instanceof Class ? ((Class>) type).getName() : type.toString();
}
}
static public class GenericArrayTypeImpl implements GenericArrayType {
final public Type genericComponentType;
public GenericArrayTypeImpl(Type ct) {
genericComponentType = ct;
}
public static GenericArrayTypeImpl make(Type ct) {
return new GenericArrayTypeImpl(ct);
}
public Type getGenericComponentType() {
return genericComponentType;
}
public String toString() {
return getGenericComponentType().getTypeName() + "[]";
}
@Override
public boolean equals(Object o) {
if (o instanceof GenericArrayType) {
GenericArrayType that = (GenericArrayType) o;
return Objects.equals(genericComponentType, that.getGenericComponentType());
} else
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(genericComponentType);
}
}
public interface ILASClassLoader {
public Class> defineLASClass(String name, IF0 generateClass);
public Object rememberClassBytes(boolean rememberClassBytes);
}
static public class LASClassDef extends HasTokenRangeWithSrc {
final public LASClassDef setUserGivenName(String userGivenName) {
return userGivenName(userGivenName);
}
public LASClassDef userGivenName(String userGivenName) {
this.userGivenName = userGivenName;
return this;
}
final public String getUserGivenName() {
return userGivenName();
}
public String userGivenName() {
return userGivenName;
}
public String userGivenName;
final public LASClassDef setClassDefPrefix(String classDefPrefix) {
return classDefPrefix(classDefPrefix);
}
public LASClassDef classDefPrefix(String classDefPrefix) {
this.classDefPrefix = classDefPrefix;
return this;
}
final public String getClassDefPrefix() {
return classDefPrefix();
}
public String classDefPrefix() {
return classDefPrefix;
}
public String classDefPrefix = "userCode.";
final public LASClassDef setFullCompilation(boolean fullCompilation) {
return fullCompilation(fullCompilation);
}
public LASClassDef fullCompilation(boolean fullCompilation) {
this.fullCompilation = fullCompilation;
return this;
}
final public boolean getFullCompilation() {
return fullCompilation();
}
public boolean fullCompilation() {
return fullCompilation;
}
public boolean fullCompilation = false;
final public LASClassDef setVerbose(boolean verbose) {
return verbose(verbose);
}
public LASClassDef verbose(boolean verbose) {
this.verbose = verbose;
return this;
}
final public boolean getVerbose() {
return verbose();
}
public boolean verbose() {
return verbose;
}
public boolean verbose = true;
final public LASClassDef setSuperClass(Type superClass) {
return superClass(superClass);
}
public LASClassDef superClass(Type superClass) {
this.superClass = superClass;
return this;
}
final public Type getSuperClass() {
return superClass();
}
public Type superClass() {
return superClass;
}
public Type superClass = Object.class;
public List fields = new ArrayList();
public List methods = new ArrayList();
public List methodBodies = new ArrayList();
public List interfaces = new ArrayList();
public GazelleV_LeftArrowScript.FunctionDef initializerMethod;
public List initializers = new ArrayList();
public BitSet isFieldInitializer = new BitSet();
static public class FieldDef {
final public FieldDef setName(String name) {
return name(name);
}
public FieldDef name(String name) {
this.name = name;
return this;
}
final public String getName() {
return name();
}
public String name() {
return name;
}
public String name;
final public FieldDef setType(Type type) {
return type(type);
}
public FieldDef type(Type type) {
this.type = type;
return this;
}
final public Type getType() {
return type();
}
public Type type() {
return type;
}
public Type type;
final public FieldDef setInitializer(GazelleV_LeftArrowScript.Evaluable initializer) {
return initializer(initializer);
}
public FieldDef initializer(GazelleV_LeftArrowScript.Evaluable initializer) {
this.initializer = initializer;
return this;
}
final public GazelleV_LeftArrowScript.Evaluable getInitializer() {
return initializer();
}
public GazelleV_LeftArrowScript.Evaluable initializer() {
return initializer;
}
public GazelleV_LeftArrowScript.Evaluable initializer;
}
public String structForHash() {
return GazelleV_LeftArrowScript.scriptStruct(litorderedmap("userGivenName", userGivenName, "fields", fields, "methods", methods, "fullCompilation", fullCompilation));
}
public String classHash_cache;
public String classHash() {
if (classHash_cache == null)
classHash_cache = classHash_load();
return classHash_cache;
}
public String classHash_load() {
String struct = structForHash();
if (verbose)
print("structForHash", struct);
return md5(struct);
}
public String finalClassName() {
return classDefPrefix() + finalClassNameWithoutPrefix();
}
public String finalClassNameWithoutPrefix() {
return or2(userGivenName, "C") + "_" + classHash();
}
public byte[] toBytes_cache;
public byte[] toBytes() {
if (toBytes_cache == null)
toBytes_cache = toBytes_load();
return toBytes_cache;
}
public byte[] toBytes_load() {
ClassMaker classMaker = new ClassMaker(finalClassName(), className(typeToClass(superClass)), mapToStringArray(interfaces, i -> className(typeToClass(i))));
var cp = classMaker.getConstantPool();
for (var field : fields) {
var type = field.type;
var fg = new FieldGen(Const.ACC_PUBLIC, typeToBCELType(type), field.name, cp);
if (type instanceof ParameterizedType)
fg.addAttribute(new org.apache.bcel.classfile.Signature(cp.addUtf8("Signature"), 2, cp.addUtf8(typeToVMSignature((ParameterizedType) type)), cp.getConstantPool()));
classMaker.addField(fg);
}
if (nempty(initializers)) {
methods.add(initializerMethod = new GazelleV_LeftArrowScript.FunctionDef("$initFields", new String[0], new GazelleV_LeftArrowScript.Script(initializers)).returnType(void.class));
if (!hasUserDefinedDefaultConstructor())
methods.add(new GazelleV_LeftArrowScript.FunctionDef("", new String[0], new GazelleV_LeftArrowScript.Script(emptyList())).returnType(void.class));
}
for (var method : methods) if (fullCompilation)
fullyCompileMethod(classMaker, method);
else
semiCompileMethod(classMaker, method);
if (!hasUserDefinedDefaultConstructor())
classMaker.addDefaultConstructor();
if (srcRef() != null)
classMaker.addField(new FieldGen(Const.ACC_PUBLIC | Const.ACC_STATIC, classToBCELType(TokenRangeWithSrc.class), srcRefField(), classMaker.getConstantPool()));
return classMaker.toBytes();
}
public TokenRangeWithSrc srcRef() {
return tokenRangeWithSrc();
}
public void addToInitializerMethod(FieldDef field) {
isFieldInitializer.set(l(initializers));
initializers.add(new GazelleV_LeftArrowScript.SetField(new GazelleV_LeftArrowScript.GetVar("this"), field.name, field.initializer));
}
public boolean hasUserDefinedDefaultConstructor() {
return any(methods, m -> m.isConstructor() && empty(m.args));
}
public void semiCompileMethod(ClassMaker classMaker, GazelleV_LeftArrowScript.FunctionDef method) {
int iMethod = l(methodBodies);
methodBodies.add(method);
String bodyFieldName = "_body" + iMethod;
classMaker.addField(new FieldGen(Const.ACC_PUBLIC | Const.ACC_STATIC, classToBCELType(GazelleV_LeftArrowScript.Evaluable.class), bodyFieldName, classMaker.getConstantPool()));
int nArgs = l(method.args);
MethodMaker mm = new MethodMaker(classMaker.cg(), Const.ACC_PUBLIC, typeToBCEL(method.returnType), method.name, mapToArray(__41 -> typeToBCEL(__41), method.argTypes));
int iThis = 0, iCtx = mm.frameSize;
if (method.isConstructor()) {
mm.aload(iThis);
mm.invokeConstructor(typeToClass(superClass));
if (initializerMethod != null) {
mm.aload(iThis);
mm.il.append(mm.factory.createInvoke(classMaker.className(), initializerMethod.name, mm.wrapType(void.class), mm.wrapTypes(new Class[0]), Const.INVOKESPECIAL));
}
}
mm.newObject(FlexibleVarContext.class);
mm.astore(iCtx);
mm.aload(iCtx);
mm.stringConstant("this");
mm.aload(iThis);
mm.invokeVirtual(VarContext.class, void.class, "put", String.class, Object.class);
for (int iArg = 0; iArg < nArgs; iArg++) {
mm.aload(iCtx);
mm.stringConstant(method.args[iArg]);
mm.aloadArgWithAutoboxing(iArg);
mm.invokeVirtual(VarContext.class, void.class, "put", String.class, Object.class);
}
mm.getStaticField(classMaker.className(), bodyFieldName, GazelleV_LeftArrowScript.Evaluable.class);
mm.aload(iCtx);
mm.invokeInterface(GazelleV_LeftArrowScript.Evaluable.class, Object.class, "get", VarContext.class);
Type type = method.returnType();
if (type == void.class)
mm._return();
else {
if (type instanceof Class && isPrimitiveType((Class) type)) {
Class c = (Class) type;
Class boxed = primitiveToBoxedType(c);
mm.checkCast(typeToBCEL(boxed));
mm.invokeVirtual(boxed, c, c + "Value");
mm.returnPrimitive(c);
} else {
if (type != Object.class)
mm.checkCast(typeToBCEL(type));
mm.areturn();
}
}
mm.done();
}
public void fullyCompileMethod(ClassMaker classMaker, GazelleV_LeftArrowScript.FunctionDef method) {
MethodMaker mm = new MethodMaker(classMaker, typeToClass(method.returnType()), method.name, repArray(Class.class, Object.class, l(method.args)));
var tbc = new LASToByteCode(mm) {
public JVMStackCellType compileGetVar(GazelleV_LeftArrowScript.GetVar code) {
if (eq(code.var, "this")) {
mm.aload(0);
return JVMStackCellType.objValue;
}
int iArg = indexOf(method.args, code.var);
if (iArg >= 0) {
mm.aload(iArg + 1);
return JVMStackCellType.objValue;
}
return super.compileGetVar(code);
}
};
tbc.postConversion = stackTop -> mm.convertToObject(stackTop);
tbc.compileScript(method.body);
mm.areturn();
mm.done();
}
public void init(Class c) {
for (int iMethod = 0; iMethod < l(methodBodies); iMethod++) {
String bodyFieldName = "_body" + iMethod;
set(c, bodyFieldName, methodBodies.get(iMethod).body);
}
setOpt(c, srcRefField(), srcRef());
}
public ResolvableLASClass resolvable(ILASClassLoader lasClassLoader) {
return new ResolvableLASClass(lasClassLoader, this);
}
public Object typeToBCEL(LASValueDescriptor descriptor) {
return or(descriptor == null ? null : descriptor.javaClass(), Object.class);
}
public Object typeToBCEL(Type type) {
{
var __1 = resolvableClassToName(type);
if (__1 != null)
return __1;
}
return typeToClass(type);
}
public void addField(FieldDef field) {
fields.add(field);
if (field.initializer != null)
addToInitializerMethod(field);
}
public String srcRefField() {
return "__srcRef";
}
}
static public class HasTokenRangeWithSrc implements IHasTokenRangeWithSrc {
final public HasTokenRangeWithSrc setTokenRangeWithSrc(TokenRangeWithSrc tokenRangeWithSrc) {
return tokenRangeWithSrc(tokenRangeWithSrc);
}
public HasTokenRangeWithSrc tokenRangeWithSrc(TokenRangeWithSrc tokenRangeWithSrc) {
this.tokenRangeWithSrc = tokenRangeWithSrc;
return this;
}
final public TokenRangeWithSrc getTokenRangeWithSrc() {
return tokenRangeWithSrc();
}
public TokenRangeWithSrc tokenRangeWithSrc() {
return tokenRangeWithSrc;
}
public TokenRangeWithSrc tokenRangeWithSrc;
}
static public class SimpleLeftToRightParser extends Meta {
public String text;
public List