Java "Machine"

         
package nova;
import java.math.*;
import java.util.*;
/**
* Warranty & Liability
* To the extent permitted by applicable law and unless explicitly
* otherwise agreed upon, XLOG Technologies AG makes no warranties
* regarding the provided information. XLOG Technologies AG assumes
* no liability that any problems might be solved with the information
* provided by XLOG Technologies AG.
*
* Rights & License
* All industrial property rights regarding the information - copyright
* and patent rights in particular - are the sole property of XLOG
* Technologies AG. If the company was not the originator of some
* excerpts, XLOG Technologies AG has at least obtained the right to
* reproduce, change and translate the information.
*
* Reproduction is restricted to the whole unaltered document. Reproduction
* of the information is only allowed for non-commercial uses. Selling,
* giving away or letting of the execution of the library is prohibited.
* The library can be distributed as part of your applications and libraries
* for execution provided this comment remains unchanged.
*
* Restrictions
* Only to be distributed with programs that add significant and primary
* functionality to the library. Not to be distributed with additional
* software intended to replace any components of the library.
*
* Trademarks
* Jekejeke is a registered trademark of XLOG Technologies AG.
*/
public final class Machine {
public static final Object[] VOID_ARGS = new Object[0];
public static Store.Bind trail = null;
public static Choice redo = null;
public static Object call = null;
/**
* Create an error term from a message.
*
* @param beta The message.
* @return Compound The error term.
*/
public static Handler.Problem make_error(Object beta) {
return new Handler.Problem(new Store.Compound("error",
new Object[]{beta, fetch_stack(ctx)}));
}
public static Object[] display_new(int size) {
if (size == 0) {
return null;
} else {
Object[] display = new Object[size];
for (int i = 0; i < size; i++)
display[i] = Store.ANON_VAR;
return display;
}
}
/**
* Retrieve the current stack.
*
* @param buf The context.
* @return The current stack.
*/
private static Object fetch_stack(Object buf) {
Store.Provable temp = Store.pred_link("sys_including", 3);
if (temp == null || (!Store.is_logical(temp.func) &&
!Store.is_stick(temp.func)))
return "[]";
Store.Clause[] data = Store.snapshot_peek(temp.func);
Store.Structure back = null;
Object res = null;
for (int i = 0; i < data.length; i++) {
Store.Clause clause = data[i];
Object[] display = display_new(clause.size);
Store.Structure alpha = (Store.Structure)exec_frame(
"sys_including", clause.head, display);
if (!alpha.args[1].equals(buf))
continue;
alpha = fetch_frame(alpha);
alpha = new Store.Compound(".", new Object[]{alpha, Store.UNDEF_OBJ});
if (back == null) {
res = alpha;
} else {
back.args[1] = alpha;
}
back = alpha;
}
if (back == null) {
res = "[]";
} else {
back.args[1] = "[]";
}
return res;
}
private static Object exec_frame(Object functor,
Object[] head, Object[] display) {
if (head.length > 0) {
temp_display = display;
Object[] args = new Object[head.length];
for (int i = 0; i < args.length; i++)
args[i] = exec_build(head[i]);
temp_display = null;
return new Store.Compound(functor, args);
} else {
return functor;
}
}
public static Store.Structure fetch_frame(Store.Structure alpha) {
String file = (String)alpha.args[0];
int k1 = file.lastIndexOf('/');
int k2 = file.lastIndexOf('\\');
String name = file.substring(Math.max(k1, k2)+1);
runtime.Source stream = (runtime.Source)alpha.args[2];
return new Store.Compound("frame",
new Object[]{"including", name,
Integer.valueOf(stream.lineno)});
}
/**
* Create a Prolog compound indicator.
*
* @param functor The functor.
* @param arity The arity.
* @return Compound The Prolog compound indicator.
*/
public static Object make_indicator(Object functor, int arity) {
return new Store.Compound("/", new Object[]{
Store.site_name(functor),
Integer.valueOf(arity)});
}
/**************************************************************/
/* Garbage Collection */
/**************************************************************/
/**
* Retrieve the real time.
*
* @return The real time.
*/
public static double real_time() {
return System.nanoTime() / 1000000.0;
}
/**
* Retrieve the used memory.
*
* @return The used memory, or zero.
*/
public static long used_memory() {
return Runtime.getRuntime().totalMemory() -
Runtime.getRuntime().freeMemory();
}
/**
* Retrieve the max memory.
*
* @return The max memory, or zero.
*/
public static long max_memory() {
long maxmem = Runtime.getRuntime().maxMemory();
return (maxmem == Long.MAX_VALUE ? 0 : maxmem);
}
public static double gc_time = 0.0;
public static double user_time = 0.0;
private static double gc_last = 0.0;
public static long gc_maxinfs = 352000L;
public static int gc_mask = Store.VAR_MASK_ODD;
public static long gc_enter = 0;
private static long gc_tick = gc_maxinfs;
private static long gc_tack = 60*gc_maxinfs;
private static long gc_tock = 3600*gc_maxinfs;
public static final long gc_maxmem = max_memory();
/**
* Garbage collection policy:
* - Regular major GC based on metronome tock
* - Emergency major GC based on soft limit
* - Otherwise perform minor GC
* - Always adapt metronom tick
*/
private static void gc_run() {
gc_time -= real_time();
if (gc_enter >= gc_tock) {
gc_major();
gc_tock += 3600*gc_maxinfs;
} else if (gc_maxmem != 0 &&
used_memory() > gc_maxmem * 3 / 4) {
gc_major();
gc_tock += 60*gc_maxinfs;
} else {
gc_minor();
}
double val = real_time();
gc_time += val;
val = user_time + val;
double val2 = val - gc_last;
gc_last = val;
val2 = (gc_maxinfs * 1000) / val2;
gc_maxinfs = Math.round((3*gc_maxinfs + val2) / 4);
}
/**
* Perform major garbage collection.
*/
public static void gc_major() {
gc_mask ^= Store.VAR_MASK_STATE;
engine.low = 0;
engine.high = engine.serno;
engine.serno = 0;
mark_redo(null, true);
mark_trail(null, true);
adjust_redo(null);
sweep_trail(null);
}
/**
* Perform minor garbage collection.
*/
private static void gc_minor() {
mark_redo(engine.backredo, false);
mark_trail(engine.backtrail, false);
adjust_redo(engine.backredo);
sweep_trail(engine.backtrail);
}
/**************************************************************/
/* Term Marking */
/**************************************************************/
/**
* Mark a term.
*
* @param first The term.
* @param scan The serno scanning flag.
*/
public static void mark_term(Object first, boolean scan) {
Object stack = null;
for (;;) {
if (Store.is_variable(first)) {
if ((((Store.Variable)first).flags & Store.VAR_MASK_STATE) != gc_mask) {
((Store.Variable)first).flags = (((Store.Variable)first).flags & ~Store.VAR_MASK_STATE) | gc_mask;
if (scan) {
int val = ((Store.Variable)first).flags & Store.VAR_MASK_SERNO;
if (val != Store.VAR_MASK_SERNO) {
if (val > engine.serno)
engine.serno = val + 1;
if (engine.low <= val && val < engine.high) {
if (val - engine.low > engine.high - val) {
engine.high = val;
} else {
engine.low = val + 1;
}
}
}
}
if (((Store.Variable)first).instantiated != Store.UNDEF_OBJ) {
Object peek = ((Store.Variable)first).instantiated;
((Store.Variable)first).instantiated = stack;
stack = first;
first = peek;
continue;
}
}
} else if (Store.is_compound(first)) {
if ((((Store.Compound)first).walk & Store.VAR_MASK_STATE) != gc_mask) {
((Store.Compound)first).walk = (((Store.Compound)first).walk & ~Store.VAR_MASK_STATE) | gc_mask;
Object peek = ((Store.Structure)first).args[0];
((Store.Structure)first).args[0] = stack;
((Store.Compound)first).walk &= ~Store.VAR_MASK_SERNO;
stack = first;
first = peek;
continue;
}
}
while (stack != null && (Store.is_variable(stack) ||
(((Store.Compound)stack).walk & Store.VAR_MASK_SERNO) ==
((Store.Structure)stack).args.length - 1)) {
if (Store.is_variable(stack)) {
Object peek = ((Store.Variable)stack).instantiated;
((Store.Variable)stack).instantiated = first;
first = stack;
stack = peek;
} else {
Object peek = ((Store.Structure)stack).args[((Store.Compound)stack).walk & Store.VAR_MASK_SERNO];
((Store.Structure)stack).args[((Store.Compound)stack).walk & Store.VAR_MASK_SERNO] = first;
first = stack;
stack = peek;
}
}
if (stack == null) {
return;
} else {
Object peek = ((Store.Structure)stack).args[((Store.Compound)stack).walk & Store.VAR_MASK_SERNO];
((Store.Structure)stack).args[((Store.Compound)stack).walk & Store.VAR_MASK_SERNO] = first;
((Store.Compound)stack).walk++;
first = ((Store.Structure)stack).args[((Store.Compound)stack).walk & Store.VAR_MASK_SERNO];
((Store.Structure)stack).args[((Store.Compound)stack).walk & Store.VAR_MASK_SERNO] = peek;
}
}
}
/**
* Mark the continuation and the choice points.
*
* @param snap The snap.
* @param scan The serno scanning flag.
*/
private static void mark_redo(Choice snap, boolean scan) {
mark_term(call, scan);
Choice last = redo;
while (last != snap) {
mark_term(last.cont, scan);
last = last.next;
}
}
/**
* Mark the trail
*
* @param stop The stop.
* @param scan The serno scanning flag.
*/
private static void mark_trail(Store.Bind stop, boolean scan) {
Store.Bind temp = trail;
while (temp != stop) {
if (!scan && temp instanceof Store.Variable &&
(((Store.Variable)temp).flags & Store.VAR_MASK_STATE)
== Store.VAR_MASK_STATE) {
mark_term(temp, false);
} else if (temp instanceof Store.Undo) {
mark_term(temp.instantiated, scan);
}
temp = temp.tail;
}
}
/**************************************************************/
/* Variable Sweep */
/**************************************************************/
/**
* Adjust the markers into the trail.
*
* @param snap The snap.
*/
private static void adjust_redo(Choice snap) {
Choice last = redo;
while (last != snap) {
Store.Bind temp = last.mark;
while (temp != null) {
if (temp instanceof Store.Variable &&
(((Store.Variable)temp).flags & Store.VAR_MASK_STATE)
== gc_mask) {
break;
} else if (temp instanceof Store.Undo) {
break;
} else {
temp = temp.tail;
}
}
last.mark = temp;
last = last.next;
}
engine.backredo = redo;
}
/**
* Sweep the trail.
*
* @param stop The stop.
*/
private static void sweep_trail(Store.Bind stop) {
Store.Bind temp = trail;
Store.Bind back = null;
while (temp != stop) {
Store.Bind term = temp;
temp = term.tail;
if (term instanceof Store.Variable &&
(((Store.Variable)term).flags & Store.VAR_MASK_STATE)
== gc_mask) {
if (back != null) {
back.tail = term;
} else {
trail = term;
}
back = term;
} else if (term instanceof Store.Undo) {
if (back != null) {
back.tail = term;
} else {
trail = term;
}
back = term;
} else {
term.instantiated = Store.UNDEF_OBJ;
term.tail = null;
}
}
if (back != null) {
back.tail = stop;
} else {
trail = stop;
}
engine.backtrail = trail;
}
/**************************************************************/
/* Clause Loops */
/**************************************************************/
public static final int SYS_MASK_ASYNC_MODE = 0x00000001;
public static final int SYS_MASK_ALLOW_YIELD = 0x00000008;
public static final int SYS_MASK_FULL_ASYNC =
SYS_MASK_ASYNC_MODE | SYS_MASK_ALLOW_YIELD;
/**
* Set the continuation.
*
* @param term The continuation.
*/
public static void cont(Object term) {
call = term;
}
/**
* Solve Prolog goals.
*
* @param snap The choice point boundary.
* @param stop The continuation boundary.
* @param found True for call, and false for redo.
* @return True if execution succeeds, otherwise false.
*/
private static Object solve(Choice snap, Object stop, Object found) {
for (; ; ) {
if (found == Boolean.TRUE) {
if (gc_enter >= gc_tick) {
if (gc_enter >= gc_tack) {
gc_run();
gc_tack += 60*gc_maxinfs;
}
gc_tick += gc_maxinfs;
if ((engine.flags & SYS_MASK_ASYNC_MODE) != 0)
return immediate_promise();
}
if (call != stop) {
gc_enter++;
Object goal = ((Store.Structure) call).args[0];
Store.Provable peek = lookup_pred(goal);
if (peek == null || (peek.flags & Store.MASK_PRED_ARITH) != 0)
throw make_error(new Store.Compound("existence_error",
new Object[]{"procedure", make_indicator_term(goal)}));
Object[] args;
if (Store.is_structure(goal)) {
args = ((Store.Structure) goal).args;
} else {
args = VOID_ARGS;
}
if ((peek.flags & Store.MASK_PRED_TEST) != 0) {
if (!((Handler.Check) peek.func).run(args)) {
found = Boolean.FALSE;
} else {
call = ((Store.Structure) call).args[1];
found = Boolean.TRUE;
}
} else if ((peek.flags & Store.MASK_PRED_SPECIAL) != 0) {
found = ((Handler.Builtin) peek.func).run(args);
} else {
Store.Logical rope = Store.defined_pred(peek, args);
found = solve2_rope(args, Store.snapshot_rope(rope), 0, null);
}
} else {
break;
}
} else if (found == Boolean.FALSE) {
if (redo != snap) {
Choice choice = redo;
Object goal = release(choice.mark);
if (goal == Store.UNDEF_OBJ) {
drain(choice.next);
call = choice.cont;
found = choice.func.run(choice.data, choice.at, choice);
} else {
found = new Store.Compound(".", new Object[]{"fail", call});
call = new Store.Compound(".", new Object[]{goal, found});
found = Boolean.TRUE;
}
} else {
break;
}
} else {
break;
}
}
return found;
}
private static Handler.Promise immediate_promise() {
return new Handler.Promise(() -> {
try {
Thread.sleep(0);
} catch (InterruptedException x) {
/* */
}
});
}
/**
* Release variable bindings.
*
* @param mark The trail mark.
*/
public static void unbind(Store.Bind mark) {
while (mark != trail) {
Store.Bind temp = trail;
trail = temp.tail;
if (engine.backtrail == temp)
engine.backtrail = trail;
temp.instantiated = Store.UNDEF_OBJ;
temp.tail = null;
}
}
/**
* Release variable bindings or find a undo goal.
*
* @param mark The trail mark.
* @return Undefined if release completed, otherwise the undo goal.
*/
public static Object release(Store.Bind mark) {
while (mark != trail) {
Store.Bind temp = trail;
trail = temp.tail;
if (engine.backtrail == temp)
engine.backtrail = trail;
if (temp instanceof Store.Undo) {
Object goal = temp.instantiated;
temp.instantiated = Store.UNDEF_OBJ;
temp.tail = null;
return goal;
} else {
temp.instantiated = Store.UNDEF_OBJ;
temp.tail = null;
}
}
return Store.UNDEF_OBJ;
}
/******************************************************************/
/* Signal Handling */
/******************************************************************/
/**
* Check and throw the signal message.
*/
private static void check_signal() {
if (engine.signal == Store.UNDEF_OBJ)
return;
Object msg = engine.signal;
engine.signal = Store.UNDEF_OBJ;
msg = melt_quote(msg);
throw make_error(msg);
}
public static Object melt_quote(Object first) {
if (Store.is_quote(first)) {
temp_display = display_new(((Store.Quote)first).size);
Object res = exec_build(((Store.Quote)first).skel);
temp_display = null;
return res;
} else {
return first;
}
}
private static void unwind_handlers(Throwable err) {
err = map_throwable(err);
Object found = Store.stack_peek(engine.handlers);
while (found != null) {
Object peek = cutter((Choice)found);
Object goal = release(redo.mark);
if (goal != Store.UNDEF_OBJ) {
Object beta = (err instanceof Handler.Problem ? ((Handler.Problem) err).term : err);
found = new Store.Compound("os_raise", new Object[]{beta});
found = new Store.Compound(".", new Object[]{found, call});
call = new Store.Compound(".", new Object[]{goal, found});
return;
}
if (peek != Store.UNDEF_OBJ) {
drain(redo.next);
Object beta = (err instanceof Handler.Problem ? ((Handler.Problem) err).term : err);
found = new Store.Compound("os_raise", new Object[]{beta});
found = new Store.Compound(".", new Object[]{found, call});
call = new Store.Compound(".", new Object[]{peek, found});
return;
}
Store.stack_pop(engine.handlers);
drain(((Choice) found).next);
call = ((Choice) found).cont;
found = ((Store.Structure) call).args[0];
call = ((Store.Structure) call).args[1];
peek = Store.site_name(((Store.Structure) found).functor);
if ("sys_trap".equals(peek)) {
Object beta = (err instanceof Handler.Problem ? ((Handler.Problem) err).term : err);
if (unify(((Store.Structure) found).args[1], beta))
break;
} else if ("shield".equals(peek)) {
engine.flags |= SYS_MASK_ASYNC_MODE;
} else if ("unshield".equals(peek)) {
engine.flags &= ~SYS_MASK_ASYNC_MODE;
} else {
throw new IllegalArgumentException("illegal handler");
}
found = Store.stack_peek(engine.handlers);
}
if (found == null)
sneaky(err);
found = Store.deref(((Store.Structure) found).args[2]);
call = new Store.Compound(".", new Object[]{found, call});
}
private static Throwable map_throwable(Throwable err) {
if (err instanceof StackOverflowError) {
err = make_error(new Store.Compound("system_error",
new Object[]{"stack_overflow"}));
} else if (err instanceof OutOfMemoryError) {
err = make_error(new Store.Compound("system_error",
new Object[]{"out_of_memory"}));
}
return err;
}
/**
* https://www.baeldung.com/java-sneaky-throws
*/
public static <E extends Throwable> void sneaky(Throwable x) throws E {
throw (E) x;
}
/**
* Cut to the choice point.
*
* @param choice The choice point mark.
*/
public static void drain(Choice choice) {
while (choice != redo) {
Choice temp = redo;
redo = temp.next;
if (engine.backredo == temp)
engine.backredo = redo;
}
}
/**
* Cut to the choice point or find a cleanup goal.
*
* @param choice The choice point mark.
* @return Undefined if cut completed, otherwise the cleanup goal.
*/
public static Object cutter(Choice choice) {
while (choice != redo) {
Choice temp = redo;
Object peek = temp.cont;
peek = ((Store.Structure)peek).args[0];
if (Store.is_structure(peek) &&
"sys_cleanup".equals(Store.site_name(((Store.Structure) peek).functor)) &&
((Store.Structure) peek).args.length == 1)
return Store.deref(((Store.Structure) peek).args[0]);
redo = temp.next;
if (engine.backredo == temp)
engine.backredo = redo;
}
return Store.UNDEF_OBJ;
}
/******************************************************************/
/* Linked Provables */
/******************************************************************/
/**
* Lookup a predicate.
*
* @param goal The goal.
* @return Provable The predicate or null.
*/
public static Store.Provable lookup_pred(Object goal) {
Object functor;
int arity;
if (Store.is_structure(goal)) {
functor = ((Store.Structure) goal).functor;
arity = ((Store.Structure) goal).args.length;
} else {
functor = goal;
arity = 0;
}
return Store.resolve_link(functor, arity);
}
/**
* Lookup an evaluable function.
*
* @param expr The arithmetic expression.
* @return Provable The evaluable function or null.
*/
private static Store.Provable lookup_eval(Object expr) {
Object functor;
int arity;
if (Store.is_structure(expr)) {
functor = ((Store.Structure) expr).functor;
arity = ((Store.Structure) expr).args.length;
} else {
functor = expr;
arity = 0;
}
return Store.resolve_link(functor, arity + 1);
}
public static Object make_indicator_term(Object goal) {
Object functor;
int arity;
if (Store.is_structure(goal)) {
Store.Structure cmp = (Store.Structure) goal;
functor = cmp.functor;
arity = cmp.args.length;
} else {
functor = goal;
arity = 0;
}
return make_indicator(functor, arity);
}
private static Object solve_rope(Object rope, int at, Choice choice) {
Object[] args;
Object goal = ((Store.Structure) call).args[0];
if (Store.is_structure(goal)) {
args = ((Store.Structure) goal).args;
} else {
args = VOID_ARGS;
}
return solve2_rope(args, rope, at, choice);
}
/**
* Search a Prolog clause and add it to the continuation.
*
* @param paras The called goal.
* @param data The clause list.
* @param at The clause index.
* @param choice The choice point for reuse or null.
* @return boolean True if search succeeds, otherwise false.
*/
static Object solve2_rope(Object[] paras, Object data, int at, Choice choice) {
Store.Bind mark = trail;
Store.Clause[] rope = (Store.Clause[]) data;
while (at < rope.length) {
Store.Clause clause = rope[at++];
Object[] display = display_new(clause.size);
if (exec_head(clause.head, display, paras)) {
int peek = clause.cutvar;
if (peek != -1)
display[peek] = redo;
if (at < rope.length) {
if (choice == null) {
choice = new Choice(Machine::solve_rope, rope, at, mark);
} else {
choice.at = at;
}
redo = choice;
if (exec_check(clause.body, display))
return Boolean.TRUE;
if (redo != choice)
return Boolean.FALSE;
redo = choice.next;
} else {
return Boolean.valueOf(exec_check(clause.body, display));
}
}
unbind(mark);
}
return Boolean.FALSE;
}
public static final class Choice {
public Handler.Callback func;
public Object data;
public int at;
public Store.Bind mark;
public Object cont;
public Choice next;
/**
* Create a choice point.
*
* @param func The choice point handler.
* @param data The choice point data.
* @param at The choice point index.
* @param mark The trail mark.
*/
public Choice(Handler.Callback func, Object data, int at, Store.Bind mark) {
this.func = func;
this.data = data;
this.at = at;
this.mark = mark;
this.cont = call;
this.next = redo;
}
}
/**
* Sets the choice point.
*
* @param choice The new choice point.
*/
public static void more(Choice choice) {
redo = choice;
}
/**************************************************************/
/* Terms */
/**************************************************************/
/**
* Check whether an object is an atom.
*
* @param obj The object.
* @return boolean True if the object is an atom, otherwise false.
*/
public static boolean is_atom(Object obj) {
return obj instanceof String;
}
/**
* Check whether an object is a number.
*
* @param obj The object.
* @return boolean True if the object is a number, otherwise false.
*/
public static boolean is_number(Object obj) {
return obj instanceof Number;
}
/**
* Check whether an object is an integer.
*
* @param obj The object.
* @return boolean True if the object is an integer, otherwise false.
*/
public static boolean is_integer(Object obj) {
return (obj instanceof Integer) || (obj instanceof BigInteger);
}
/**
* Check whether an object is a float.
*
* @param obj The object.
* @return boolean True if the object is a float, otherwise false.
*/
public static boolean is_float(Object obj) {
return obj instanceof Double;
}
/**
* Check whether an object is a bigint.
*
* @param alpha The object.
* @return boolean True if the object is a bignum, otherwise false.
*/
public static boolean is_bigint(Object alpha) {
return alpha instanceof BigInteger;
}
/**
* Check whether an object is a special value.
*
* @param alpha The object.
* @return boolean True if the object is a special value, otherwise false.
*/
public static boolean is_special(Object alpha) {
return (alpha instanceof Double &&
!Double.isFinite(((Double)alpha).doubleValue()));
}
/**************************************************************/
/* Albufeira Lazy */
/**************************************************************/
public static Object[] temp_display;
public static boolean is_pending(Object template) {
if (template == Store.ANON_VAR) {
return true;
} else if (Store.is_place(template)) {
return true;
} else {
return false;
}
}
public static Object exec_deref(Object template) {
if (template == Store.ANON_VAR) {
return template;
} else if (Store.is_place(template)) {
int index = ((Store.Place) template).index;
Object peek = temp_display[index];
if (peek == Store.ANON_VAR) {
return template;
} else {
return Store.deref(peek);
}
} else {
return Store.deref(template);
}
}
/**************************************************************/
/* Albufeira Modes */
/**************************************************************/
public static Object exec_build(Object template) {
Store.Structure back = null;
for (; ; ) {
if (template == Store.ANON_VAR) {
template = new Store.Variable();
break;
} else if (Store.is_place(template)) {
int index = ((Store.Place) template).index;
template = temp_display[index];
if (template == Store.ANON_VAR) {
template = new Store.Variable();
temp_display[index] = template;
} else {
template = Store.deref(template);
}
break;
} else if (Store.is_skeleton(template)) {
Object[] args = new Object[((Store.Skeleton) template).args.length];
args[args.length - 1] = back;
back = new Store.Compound(((Store.Skeleton) template).functor, args);
template = ((Store.Skeleton) template).args;
int i = 0;
for (; i < args.length - 1; i++)
args[i] = exec_build(((Object[])template)[i]);
template = ((Object[])template)[i];
} else {
template = Store.deref(template);
break;
}
}
while (back != null) {
Object peek = back.args[back.args.length - 1];
back.args[back.args.length - 1] = template;
template = back;
back = (Store.Structure) peek;
}
return template;
}
public static boolean exec_unify(Object template, Object alpha) {
for (; ; ) {
if (template == Store.ANON_VAR) {
return true;
} else if (Store.is_place(template)) {
int index = ((Store.Place) template).index;
template = temp_display[index];
if (template == Store.ANON_VAR) {
temp_display[index] = Store.deref(alpha);
return true;
} else {
return unify(alpha, template);
}
} else if (Store.is_skeleton(template)) {
alpha = Store.deref(alpha);
if (Store.is_variable(alpha)) {
Object[] args = new Object[((Store.Skeleton) template).args.length];
bind(new Store.Compound(((Store.Skeleton) template).functor, args), (Store.Variable) alpha);
template = ((Store.Skeleton) template).args;
for (int i = 0; i < args.length; i++)
args[i] = exec_build(((Object[])template)[i]);
return true;
} else if (Store.is_structure(alpha)) {
if (((Store.Skeleton) template).args.length !=
((Store.Structure) alpha).args.length)
return false;
if (!Objects.equals(((Store.Skeleton) template).functor,
((Store.Structure) alpha).functor))
return false;
template = ((Store.Skeleton) template).args;
alpha = ((Store.Structure) alpha).args;
int i = 0;
for (; i < ((Object[])template).length - 1; i++)
if (!exec_unify(((Object[])template)[i], ((Object[])alpha)[i]))
return false;
template = ((Object[])template)[i];
alpha = ((Object[])alpha)[i];
} else {
return false;
}
} else {
return unify(template, alpha);
}
}
}
/**
* Bind a variable to a term.
*
* @param source The Prolog term.
* @param term The variable.
*/
public static void bind(Object source, Store.Bind term) {
term.instantiated = source;
term.tail = trail;
if (term instanceof Store.Variable &&
(((Store.Variable)term).flags & Store.VAR_MASK_STATE)
== gc_mask)
((Store.Variable)term).flags |= Store.VAR_MASK_STATE;
trail = term;
}
/**************************************************************/
/* Albufeira Clauses */
/**************************************************************/
public static Object exec_body(Object[] code, Object[] display, Object stop) {
temp_display = display;
Store.Structure back = null;
Object res = null;
for (int i = 0; i < code.length; i++) {
Object goal = exec_build(code[i]);
Store.Structure temp = new Store.Compound(".", new Object[]{goal, Store.UNDEF_OBJ});
if (back == null) {
res = temp;
} else {
back.args[1] = temp;
}
back = temp;
}
if (back == null) {
res = stop;
} else {
back.args[1] = stop;
}
temp_display = null;
return res;
}
public static boolean exec_head(Object[] code, Object[] display,
Object[] aux) {
if (aux.length != code.length)
return false;
temp_display = display;
for (int i = 0; i < code.length; i++) {
if (!exec_unify(code[i], aux[i])) {
temp_display = null;
return false;
}
}
temp_display = null;
return true;
}
/**************************************************************/
/* Head Check */
/**************************************************************/
public static Number exec_eval(Object template) {
if (template == Store.ANON_VAR) {
throw make_error("instantiation_error");
} else if (Store.is_place(template)) {
int index = ((Store.Place) template).index;
template = temp_display[index];
if (template == Store.ANON_VAR)
throw make_error("instantiation_error");
}
template = Store.deref(template);
if (is_number(template))
return (Number) template;
Store.Provable peek = lookup_eval(template);
if (peek == null || (peek.flags & Store.MASK_PRED_ARITH) == 0)
throw make_error(new Store.Compound("type_error",
new Object[]{"evaluable", make_indicator_term(template)}));
Object[] args;
if (Store.is_structure(template)) {
args = ((Store.Structure) template).args;
} else {
args = VOID_ARGS;
}
return ((Handler.Funktion) peek.func).eval(args);
}
private static Object exec_test(Object template) {
Store.Provable peek = lookup_pred(template);
if (peek != null && (peek.flags & Store.MASK_PRED_ROGUE) != 0) {
Object choice = exec_build(((Store.Structure) template).args[0]);
template = cutter((Choice) choice);
if (template == Store.UNDEF_OBJ) {
return Boolean.TRUE;
} else {
drain(redo.next);
return template;
}
} else if (peek == null || (peek.flags & Store.MASK_PRED_TEST) == 0) {
return Store.UNDEF_OBJ;
} else {
Object[] args;
if (Store.is_structure(template)) {
args = ((Store.Structure) template).args;
} else {
args = VOID_ARGS;
}
gc_enter++;
return Boolean.valueOf(((Handler.Check) peek.func).run(args));
}
}
private static boolean exec_check(Object[] code, Object[] display) {
temp_display = display;
int i = 0;
Store.Compound back = null;
Object res = null;
for (;i < code.length;i++) {
Object goal = exec_test(code[i]);
if (goal == Store.UNDEF_OBJ)
break;
if (goal == Boolean.FALSE) {
temp_display = null;
return false;
}
if (goal == Boolean.TRUE)
continue;
goal = new Store.Compound(".", new Object[]{goal, Store.UNDEF_OBJ});
if (back == null) {
res = goal;
} else {
back.args[1] = goal;
}
back = (Store.Compound)goal;
break;
}
for (;i < code.length;i++) {
Object goal = exec_build(code[i]);
goal = new Store.Compound(".", new Object[]{goal, Store.UNDEF_OBJ});
if (back == null) {
res = goal;
} else {
back.args[1] = goal;
}
back = (Store.Compound)goal;
}
if (back == null) {
res = ((Store.Structure) call).args[1];
} else {
back.args[1] = ((Store.Structure) call).args[1];
}
temp_display = null;
call = res;
return true;
}
/**************************************************************/
/* Unification */
/**************************************************************/
/**
* Determine whether two terms unify.
* As a side effect the trail is extended, even if unification fails.
* Can handle cyclic terms and deep recursion.
*
* @param first The first term.
* @param second The second term.
* @return boolean True if the two terms unify, otherwise false.
*/
public static boolean unify(Object first, Object second) {
List stack = null;
List log = null;
try {
for (; ; ) {
first = Store.deref(first);
second = Store.deref(second);
if (Store.is_variable(first)) {
if (!Store.is_variable(second) || first != second)
bind(second, (Store.Variable) first);
} else if (Store.is_variable(second)) {
bind(first, (Store.Variable) second);
} else if (!Store.is_structure(first)) {
if (!Objects.equals(first, second))
break;
} else if (!Store.is_structure(second)) {
break;
} else if (((Store.Structure) first).args.length !=
((Store.Structure) second).args.length) {
break;
} else {
first = Store.union_find((Store.Structure) first);
second = Store.union_find((Store.Structure) second);
if (first != second) {
if (Store.is_frozen(first) && Store.is_frozen(second) &&
((Store.Frozen)first).hash != ((Store.Frozen)second).hash)
break;
if (!Objects.equals(((Store.Structure) first).functor,
((Store.Structure) second).functor))
break;
log = Store.union_add(log, (Store.Structure) first,
(Store.Structure) second);
if (0 != ((Store.Structure) first).args.length - 1) {
Store.Item item2 = new Store.Item((Store.Structure)first, second, 0);
stack = Store.stack_push(stack, item2);
}
first = ((Store.Structure) first).args[0];
second = ((Store.Structure) second).args[0];
continue;
}
}
Store.Item item = (Store.Item)Store.stack_peek(stack);
if (item == null) {
return true;
} else {
item.idx++;
first = item.first.args[item.idx];
second = ((Store.Structure)item.second).args[item.idx];
if (item.idx == item.first.args.length - 1)
Store.stack_pop(stack);
}
}
return false;
} finally {
Store.union_undo(log);
}
}
/**************************************************************/
/* Engine */
/**************************************************************/
public static final class Engine {
public Object signal;
public Runnable abort;
public int flags;
public runtime.Sink text_output;
public runtime.Sink text_error;
public runtime.Source text_input;
public int low;
public int high;
public int serno;
public Store.Bind backtrail;
public Choice backredo;
public String partition;
public Object done;
public List handlers;
/**
* Create a slow state engine.
*/
public Engine() {
this.signal = Store.UNDEF_OBJ;
this.abort = () -> { };
this.flags = 0;
this.text_output = null;
this.text_error = null;
this.text_input = null;
this.low = 0;
this.high = 0;
this.serno = 0;
this.backtrail = null;
this.partition = (Store.stage == -1 ? "system" : "user");
this.done = null;
this.handlers = null;
}
}
public static Engine engine = new Engine();
/**************************************************************/
/* Context */
/**************************************************************/
public static final String CTX_MAIN = "main";
public static final class Context {
public Store.Bind trail;
public Choice redo;
public Object call;
public int gc_mask;
public Machine.Engine ref;
public Context() {
this.trail = null;
this.redo = null;
this.call = null;
this.gc_mask = Store.VAR_MASK_ODD;
this.ref = new Machine.Engine();
this.ref.text_output = engine.text_output;
this.ref.text_error = engine.text_error;
this.ref.text_input = engine.text_input;
}
}
public static Object ctx = CTX_MAIN;
/**
* Set the task context.
*
* @param buf The context.
*/
public static void ctx_set(Object buf) {
ctx = buf;
}
/**
* Switch the task context.
*
* @param buf The context.
*/
public static void ctx_switch(Context buf) {
Store.Bind vtemp = trail;
trail = buf.trail;
buf.trail = vtemp;
Choice ctemp = redo;
redo = buf.redo;
buf.redo = ctemp;
Object otemp = call;
call = buf.call;
buf.call = otemp;
int itemp = gc_mask;
gc_mask = buf.gc_mask;
buf.gc_mask = itemp;
Machine.Engine etemp = engine;
engine = buf.ref;
buf.ref = etemp;
}
/**************************************************************/
/* Launch Sync */
/**************************************************************/
/**
* Run a compiled goal once. The goal is run with auto-yield
* disabled and promises are not accepted.
*
* @param goal The compiled goal.
*/
public static void run(Store.Goal goal) {
if (!launch(goal, CTX_MAIN, VOID_ARGS))
throw make_error(new Store.Compound("syntax_error",
new Object[]{"directive_failed"}));
}
/**
* Run a callback once, i.e. no choice point or trailing left
* behind. Callbacks are run with auto-yield disabled and
* promises are not accepted, i.e. run "stackless" on top of the
* given main stack or side stack. "stackless" because completion,
* i.e. return or exception by the callback, is the only context switch.
*
* @param form The goal or closure.
* @param buf The context or "main".
* @param paras The actual parameters.
* @return True or false.
*/
public static boolean launch(Object form, Object buf, Object[] paras) {
user_time -= real_time();
if (!CTX_MAIN.equals(buf)) {
ctx_set(buf);
ctx_switch((Context) buf);
}
int back = engine.flags & SYS_MASK_FULL_ASYNC;
engine.flags &= ~SYS_MASK_FULL_ASYNC;
Choice snap = redo;
Store.Bind mark = trail;
Object stop = call;
call = melt_form(form, paras, stop);
List data = engine.handlers;
engine.handlers = null;
Object found;
try {
for (; ; ) {
try {
found = solve(snap, stop, Boolean.TRUE);
break;
} catch (Throwable err) {
unwind_handlers(err);
}
}
} finally {
engine.handlers = data;
drain(snap);
unbind(mark);
call = stop;
engine.flags &= ~SYS_MASK_FULL_ASYNC;
engine.flags |= back;
if (!CTX_MAIN.equals(buf)) {
ctx_switch((Context) buf);
ctx_set(CTX_MAIN);
}
user_time += real_time();
}
return ((Boolean) found).booleanValue();
}
/**************************************************************/
/* Launch Async */
/**************************************************************/
/**
* Run a task once, i.e. no choice point or trailing left
* behind. Tasks are run with auto-yield enabled and promises are
* accepted, i.e. run "stackfull" on top of the given main stack
* or side stack. "stackfull" because not only completion, i.e.
* return or exception by the task, cause a context switch, but
* also await of an auto-yield or promise.
*
* @param form The goal or closure.
* @param buf The context or "main".
* @param paras The actual parameters.
* @return True or false.
*/
public static boolean launch_async(Object form, Object buf, Object[] paras) {
user_time -= real_time();
if (!CTX_MAIN.equals(buf)) {
ctx_set(buf);
ctx_switch((Context) buf);
}
int back = engine.flags & SYS_MASK_FULL_ASYNC;
engine.flags |= SYS_MASK_FULL_ASYNC;
Choice snap = redo;
Store.Bind mark = trail;
Object stop = call;
call = melt_form(form, paras, stop);
List data = engine.handlers;
engine.handlers = null;
Object found;
try {
for (; ; ) {
try {
found = solve(snap, stop, Boolean.TRUE);
if (found == Boolean.FALSE || found == Boolean.TRUE)
break;
if (!CTX_MAIN.equals(buf)) {
ctx_switch((Context) buf);
ctx_set(CTX_MAIN);
}
user_time += real_time();
((Handler.Promise) found).await();
user_time -= real_time();
if (!CTX_MAIN.equals(buf)) {
ctx_set(buf);
ctx_switch((Context) buf);
}
check_signal();
} catch (Throwable err) {
unwind_handlers(err);
}
}
} finally {
engine.handlers = data;
drain(snap);
unbind(mark);
call = stop;
engine.flags &= ~SYS_MASK_FULL_ASYNC;
engine.flags |= back;
if (!CTX_MAIN.equals(buf)) {
ctx_switch((Context) buf);
ctx_set(CTX_MAIN);
}
user_time += real_time();
}
return ((Boolean)found).booleanValue();
}
/**************************************************************/
/* Utilities */
/**************************************************************/
public static Object melt_form(Object form, Object[] paras, Object stop) {
if (Store.is_clause(form)) {
Object[] display = display_new(((Store.Clause)form).size);
if (exec_head(((Store.Clause)form).head, display, paras)) {
int peek = ((Store.Clause)form).cutvar;
if (peek != -1)
display[peek] = redo;
return exec_body(((Store.Clause)form).body, display, stop);
} else {
return stop;
}
} else if (Store.is_goal(form)) {
Object[] display = display_new(((Store.Goal)form).size);
int peek = ((Store.Goal)form).cutvar;
if (peek != -1)
display[peek] = redo;
return exec_body(((Store.Goal)form).body, display, stop);
} else {
return new Store.Compound(".", new Object[]{form, stop});
}
}
/**
* Determine the engine from a task context.
*
* @param tsk The task context.
* @return The engine.
*/
public static Machine.Engine determine_engine(Object tsk) {
if (!CTX_MAIN.equals(tsk)) {
if (!tsk.equals(ctx)) {
return ((Context) tsk).ref;
} else {
return engine;
}
} else {
if (!CTX_MAIN.equals(ctx)) {
return ((Context) ctx).ref;
} else {
return engine;
}
}
}
}