/**
* Modern Albufeira Prolog Interpreter
*
* 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.
*/
import {
Compound, defined_pred, deref, Undo, is_clause, stage,
is_compound, is_structure, is_goal, is_logical, is_place, is_skeleton,
is_stick, is_variable, Item, Variable, site_name,
MASK_PRED_ARITH, MASK_PRED_SPECIAL, MASK_PRED_TEST, MASK_PRED_ROGUE,
pred_link, resolve_link, ANON_VAR, is_quote,
snapshot_peek, snapshot_rope, stack_peek, stack_pop, stack_push,
union_find, union_add, union_undo, is_frozen,
VAR_MASK_ODD, VAR_MASK_SERNO, VAR_MASK_STATE
} from "./store.mjs";
export const VOID_ARGS = [];
export let fs;
export let url;
export let path;
export let os;
export let v8;
if (typeof window === 'undefined') {
fs = await import("node:fs");
url = await import("node:url");
path = await import("node:path");
os = await import("node:os");
v8 = await import("node:v8");
} else {
fs = undefined;
url = undefined;
path = undefined;
os = undefined;
v8 = undefined;
}
export let trail = null;
export let redo = null;
export let call = null;
/**
* Create an error term from a message.
*
* @param beta The message.
* @return Compound The error term.
*/
export function make_error(beta) {
return new Compound("error", [beta, fetch_stack(ctx)]);
}
export function display_new(size) {
if (size === 0) {
return null;
} else {
let display = new Array(size)
for (let i = 0; i < size; i++)
display[i] = ANON_VAR;
return display;
}
}
/**
* Retrieve the current stack.
*
* @param buf The context.
* @return The current stack.
*/
function fetch_stack(buf) {
let temp = pred_link("sys_including", 3);
if (temp === undefined || (!is_logical(temp.func) &&
!is_stick(temp.func)))
return "[]";
let data = snapshot_peek(temp.func);
let back = null;
let res = null;
for (let i = 0; i < data.length; i++) {
let clause = data[i];
let display = display_new(clause.size);
let alpha = exec_frame("sys_including", clause.head, display);
if (alpha.args[1] !== buf)
continue;
alpha = fetch_frame(alpha);
alpha = new Compound(".", [alpha, undefined]);
if (back === null) {
res = alpha;
} else {
back.args[1] = alpha;
}
back = alpha;
}
if (back === null) {
res = "[]";
} else {
back.args[1] = "[]";
}
return res;
}
export function exec_frame(functor, head, display) {
if (head.length > 0) {
temp_display = display;
let args = new Array(head.length);
for (let i = 0; i < args.length; i++)
args[i] = exec_build(head[i]);
temp_display = null;
return new Compound(functor, args);
} else {
return functor;
}
}
function fetch_frame(alpha) {
let file = alpha.args[0];
let k1 = file.lastIndexOf("/");
let k2 = file.lastIndexOf("\\");
let name = file.substring(Math.max(k1, k2) + 1);
let stream = alpha.args[2];
return new Compound("frame",
["including", name, stream.lineno]);
}
/**
* Create a Prolog compound indicator.
*
* @param functor The functor.
* @param arity The arity.
* @return Compound The Prolog compound indicator.
*/
export function make_indicator(functor, arity) {
return new Compound("/", [site_name(functor), arity]);
}
/**
* Compute the hash code of an object
*
* @param alpha The object.
* @return The hash code, a signed 32-bit integer
*/
export function object_hash_code(alpha) {
if (is_atom(alpha)) {
let res = 0;
for (let i = 0; i < alpha.length; i++)
res = (res * 31 + alpha.charCodeAt(i)) | 0;
return res;
} else if (is_number(alpha)) {
if (is_integer(alpha)) {
if (!is_bigint(alpha)) {
return alpha;
} else {
let sign;
if (alpha < 0) {
sign = -1;
alpha = -alpha;
} else {
sign = 1;
}
alpha = alpha.toString(16);
let res = 0;
let i = alpha.length % 8;
if (i > 0)
res = parseInt(alpha.substring(0, i), 16) | 0;
for (; i < alpha.length; i += 8)
res = (res * 31 + parseInt(alpha.substring(i, i + 8), 16)) | 0;
return (sign > 0 ? res : -res);
}
} else {
let beta = new Float64Array(1);
beta[0] = Number(alpha);
let gamma = new Int32Array(beta.buffer);
return gamma[0] ^ gamma[1];
}
} else if (alpha === null) {
return 0;
} else if (alpha === true) {
return 1231;
} else if (alpha === false) {
return 1237;
} else {
return 2467;
}
}
/**************************************************************/
/* Garbage Collection */
/**************************************************************/
/**
* Retrieve the real time.
*
* @return The real time.
*/
export function real_time() {
if (fs !== undefined) {
return (Number(process.hrtime.bigint()) / 1000000.0);
} else {
return performance.now();
}
}
/**
* Retrieve the used memory.
*
* @return The used memory, or zero.
*/
export function used_memory() {
if (fs !== undefined) {
return process.memoryUsage().heapUsed;
} else {
return (performance.memory !== undefined ?
performance.memory.usedJSHeapSize : 0);
}
}
/**
* Retrieve the max memory.
*
* @return The max memory, or zero.
*/
export function max_memory() {
if (fs !== undefined) {
return v8.getHeapStatistics().heap_size_limit;
} else {
return (performance.memory !== undefined ?
performance.memory.jsHeapSizeLimit : 0)
}
}
export let gc_time = 0.0;
export let user_time = 0.0;
let gc_last = 0.0;
export let gc_maxinfs = 128000;
export let gc_mask = VAR_MASK_ODD;
export let gc_enter = 0;
let gc_tick = gc_maxinfs;
let gc_tack = 60*gc_maxinfs;
let gc_tock = 3600*gc_maxinfs;
export let 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
*/
function 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();
}
let val = real_time();
gc_time += val;
val = user_time + val;
let 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.
*/
export function gc_major() {
gc_mask ^= 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.
*/
function 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.
*/
export function mark_term(first, scan) {
let stack = null;
for (;;) {
if (is_variable(first)) {
if ((first.flags & VAR_MASK_STATE) !== gc_mask) {
first.flags = (first.flags & ~VAR_MASK_STATE) | gc_mask;
if (scan) {
let val = first.flags & VAR_MASK_SERNO;
if (val !== 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 (first.instantiated !== undefined) {
let peek = first.instantiated;
first.instantiated = stack;
stack = first;
first = peek;
continue;
}
}
} else if (is_compound(first)) {
if ((first.walk & VAR_MASK_STATE) !== gc_mask) {
first.walk = (first.walk & ~VAR_MASK_STATE) | gc_mask;
let peek = first.args[0];
first.args[0] = stack;
first.walk &= ~VAR_MASK_SERNO;
stack = first;
first = peek;
continue;
}
}
while (stack !== null && (is_variable(stack) ||
(stack.walk & VAR_MASK_SERNO) === stack.args.length - 1)) {
if (is_variable(stack)) {
let peek = stack.instantiated;
stack.instantiated = first;
first = stack;
stack = peek;
} else {
let peek = stack.args[stack.walk & VAR_MASK_SERNO];
stack.args[stack.walk & VAR_MASK_SERNO] = first;
first = stack;
stack = peek;
}
}
if (stack === null) {
return;
} else {
let peek = stack.args[stack.walk & VAR_MASK_SERNO];
stack.args[stack.walk & VAR_MASK_SERNO] = first;
stack.walk++;
first = stack.args[stack.walk & VAR_MASK_SERNO];
stack.args[stack.walk & VAR_MASK_SERNO] = peek;
}
}
}
/**
* Mark the continuation and the choice points.
*
* @param snap The snap.
* @param scan The serno scanning flag.
*/
function mark_redo(snap, scan) {
mark_term(call, scan);
let 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.
*/
function mark_trail(stop, scan) {
let temp = trail;
while (temp !== stop) {
if (!scan && temp instanceof Variable &&
(temp.flags & VAR_MASK_STATE) === VAR_MASK_STATE) {
mark_term(temp, false);
} else if (temp instanceof Undo) {
mark_term(temp.instantiated, scan);
}
temp = temp.tail;
}
}
/**************************************************************/
/* Variable Sweep */
/**************************************************************/
/**
* Adjust the markers into the trail.
*
* @param snap The snap.
*/
function adjust_redo(snap) {
let last = redo;
while (last !== snap) {
let temp = last.mark;
while (temp !== null) {
if (temp instanceof Variable &&
(temp.flags & VAR_MASK_STATE) === gc_mask) {
break;
} else if (temp instanceof Undo) {
break;
} else {
temp = temp.tail;
}
}
last.mark = temp;
last = last.next;
}
engine.backredo = redo;
}
/**
* Sweep the trail.
*
* @param stop The stop.
*/
function sweep_trail(stop) {
let temp = trail;
let back = null;
while (temp !== stop) {
let term = temp;
temp = term.tail;
if (term instanceof Variable &&
(term.flags & VAR_MASK_STATE) === gc_mask) {
if (back !== null) {
back.tail = term;
} else {
trail = term;
}
back = term;
} else if (term instanceof Undo) {
if (back !== null) {
back.tail = term;
} else {
trail = term;
}
back = term;
} else {
term.instantiated = undefined;
term.tail = null;
}
}
if (back !== null) {
back.tail = stop;
} else {
trail = stop;
}
engine.backtrail = trail;
}
/**************************************************************/
/* Clause Loops */
/**************************************************************/
export const SYS_MASK_ASYNC_MODE = 0x00000001;
export const SYS_MASK_ALLOW_YIELD = 0x00000008;
export const SYS_MASK_FULL_ASYNC = SYS_MASK_ASYNC_MODE |
SYS_MASK_ALLOW_YIELD;
/**
* Set the continuation.
*
* @param term The continuation.
*/
export function cont(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.
*/
function solve(snap, stop, found) {
for (; ;) {
if (found === 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++;
let goal = call.args[0];
let peek = lookup_pred(goal);
if (peek === undefined || (peek.flags & MASK_PRED_ARITH) !== 0)
throw make_error(new Compound("existence_error",
["procedure", make_indicator_term(goal)]));
if (is_structure(goal)) {
goal = goal.args;
} else {
goal = VOID_ARGS;
}
if ((peek.flags & MASK_PRED_TEST) !== 0) {
if (!peek.func(goal)) {
found = false;
} else {
call = call.args[1];
found = true;
}
} else if ((peek.flags & MASK_PRED_SPECIAL) !== 0) {
found = peek.func(goal);
} else {
peek = defined_pred(peek, goal);
found = solve2_rope(goal, snapshot_rope(peek), 0, null);
}
} else {
break;
}
} else if (found === false) {
if (redo !== snap) {
let choice = redo;
let goal = release(choice.mark);
if (goal === undefined) {
drain(choice.next);
call = choice.cont;
found = choice.func(choice.data, choice.at, choice);
} else {
found = new Compound(".", ["fail", call]);
call = new Compound(".", [goal, found]);
found = true;
}
} else {
break;
}
} else {
break;
}
}
return found;
}
function immediate_promise() {
return new Promise(resolve => setDelay(resolve, 0));
}
/**
* Delay a coroutine by some milliseconds.
*
* @param proc The coroutine.
* @param delay The milliseconds.
* @return The timer.
*/
export function setDelay(proc, delay) {
if (delay === 0 && fs !== undefined) {
return setImmediate(proc);
} else {
return setTimeout(proc, delay);
}
}
/**
* Release variable bindings.
*
* @param mark The trail mark.
*/
export function unbind(mark) {
while (mark !== trail) {
let temp = trail;
trail = temp.tail;
if (engine.backtrail === temp)
engine.backtrail = trail;
temp.instantiated = undefined;
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.
*/
export function release(mark) {
while (mark !== trail) {
let temp = trail;
trail = temp.tail;
if (engine.backtrail === temp)
engine.backtrail = trail;
if (temp instanceof Undo) {
let goal = temp.instantiated;
temp.instantiated = undefined;
temp.tail = null;
return goal;
} else {
temp.instantiated = undefined;
temp.tail = null;
}
}
return undefined;
}
/******************************************************************/
/* Signal Handling */
/******************************************************************/
/**
* Check and throw the signal message.
*/
export function check_signal() {
if (engine.signal === undefined)
return;
let msg = engine.signal;
engine.signal = undefined;
msg = melt_quote(msg);
throw make_error(msg);
}
export function melt_quote(first) {
if (is_quote(first)) {
temp_display = display_new(first.size);
let res = exec_build(first.skel);
temp_display = null;
return res;
} else {
return first;
}
}
function unwind_handlers(err) {
err = map_throwable(err);
let found = stack_peek(engine.handlers);
while (found !== null) {
let peek = cutter(found);
let goal = release(redo.mark)
if (goal !== undefined) {
found = new Compound("os_raise", [err]);
found = new Compound(".", [found, call]);
call = new Compound(".", [goal, found]);
return;
}
if (peek !== undefined) {
drain(redo.next);
found = new Compound("os_raise", [err]);
found = new Compound(".", [found, call]);
call = new Compound(".", [peek, found]);
return;
}
stack_pop(engine.handlers);
drain(found.next);
call = found.cont;
found = call.args[0];
call = call.args[1];
peek = site_name(found.functor);
if ("sys_trap" === peek) {
if (unify(found.args[1], err))
break;
} else if ("shield" === peek) {
engine.flags |= SYS_MASK_ASYNC_MODE;
} else if ("unshield" === peek) {
engine.flags &= ~SYS_MASK_ASYNC_MODE;
} else {
throw new Error("illegal handler");
}
found = stack_peek(engine.handlers);
}
if (found == null)
throw err;
found = deref(found.args[2]);
call = new Compound(".", [found, call]);
}
function map_throwable(err) {
if (err instanceof RangeError && err.message.includes("stack"))
err = make_error(new Compound("system_error", ["stack_overflow"]));
return err;
}
/**
* Cut to the choice point.
*
* @param choice The choice point mark.
*/
export function drain(choice) {
while (choice !== redo) {
let 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 new choice point.
* @return Undefined if cut completed, otherwise the cleanup goal.
*/
export function cutter(choice) {
while (choice !== redo) {
let temp = redo;
let peek = temp.cont;
peek = peek.args[0];
if (is_structure(peek) &&
"sys_cleanup" === site_name(peek.functor) &&
peek.args.length === 1)
return deref(peek.args[0]);
redo = temp.next;
if (engine.backredo === temp)
engine.backredo = redo;
}
return undefined;
}
/******************************************************************/
/* Linked Provables */
/******************************************************************/
/**
* Lookup a predicate.
*
* @param goal The goal.
* @return Provable The predicate or undefined.
*/
export function lookup_pred(goal) {
let functor;
let arity;
if (is_structure(goal)) {
functor = goal.functor;
arity = goal.args.length;
} else {
functor = goal;
arity = 0;
}
return resolve_link(functor, arity);
}
/**
* Lookup an evaluable function.
*
* @param expr The arithmetic expression.
* @return Provable The evaluable function or undefined.
*/
function lookup_eval(expr) {
let functor;
let arity;
if (is_structure(expr)) {
functor = expr.functor;
arity = expr.args.length;
} else {
functor = expr;
arity = 0;
}
return resolve_link(functor, arity + 1);
}
export function make_indicator_term(goal) {
let functor;
let arity;
if (is_structure(goal)) {
functor = goal.functor;
arity = goal.args.length;
} else {
functor = goal;
arity = 0;
}
return make_indicator(functor, arity);
}
function solve_rope(rope, at, choice) {
let goal = call.args[0];
if (is_structure(goal)) {
goal = goal.args;
} else {
goal = VOID_ARGS;
}
return solve2_rope(goal, rope, at, choice);
}
/**
* Search a Prolog clause and add it to the continuation.
*
* @param paras The called goal.
* @param rope 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.
*/
function solve2_rope(paras, rope,at,choice) {
let mark = trail;
while (at < rope.length) {
let clause = rope[at++];
let display = display_new(clause.size);
if (exec_head(clause.head, display, paras)) {
let peek = clause.cutvar;
if (peek !== -1)
display[peek] = redo;
if (at < rope.length) {
if (choice === null) {
choice = new Choice(solve_rope, rope, at, mark);
} else {
choice.at = at;
}
redo = choice;
if (exec_check(clause.body, display))
return true;
if (redo !== choice)
return false;
redo = choice.next;
} else {
return exec_check(clause.body, display);
}
}
unbind(mark);
}
return false;
}
/**
* Sets the choice point.
*
* @param choice The new choice point.
*/
export function more(choice) {
redo = choice;
}
/**
* 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.
* @constructor The choice point.
*/
export function Choice(func, data, at, mark) {
this.func = func;
this.data = data;
this.at = at;
this.mark = mark;
this.cont = call;
this.next = redo;
}
/**************************************************************/
/* Terms */
/**************************************************************/
/**
* Check whether an object is an atom.
*
* @param obj The object.
* @return boolean True if the object is an atom, otherwise false.
*/
export function is_atom(obj) {
return typeof obj === "string";
}
/**
* Check whether an object is a number.
*
* @param obj The object.
* @return boolean True if the object is a number, otherwise false.
*/
export function is_number(obj) {
if (typeof obj === "number")
return true;
if (typeof obj === "bigint")
return true;
return false;
}
/**
* Check whether an object is an integer.
*
* @param obj The object.
* @return boolean True if the object is an integer, otherwise false.
*/
export function is_integer(obj) {
if (typeof obj === "number" &&
Number.isInteger(obj) &&
((-94906266 <= obj) && (obj <= 94906266)))
return true;
if (typeof obj === "bigint" &&
!((-94906266 <= obj) && (obj <= 94906266)))
return true;
return false;
}
/**
* Check whether an object is a float.
*
* @param obj The object.
* @return boolean True if the object is a float, otherwise false.
*/
export function is_float(obj) {
if (typeof obj === "number" &&
(!Number.isInteger(obj) ||
!((-94906266 <= obj) && (obj <= 94906266))))
return true;
if (typeof obj === "bigint" &&
((-94906266 <= obj) && (obj <= 94906266)))
return true;
return false;
}
/**
* Check whether an object is a bigint.
*
* @param alpha The object.
* @return boolean True if the object is a bignum, otherwise false.
*/
export function is_bigint(alpha) {
return typeof alpha === "bigint";
}
/**
* Check whether an object is a special value.
*
* @param alpha The object.
* @return boolean True if the object is a special value, otherwise false.
*/
export function is_special(alpha) {
return (typeof alpha === "number" &&
!Number.isFinite(alpha));
}
/**************************************************************/
/* Albufeira Lazy */
/**************************************************************/
let temp_display = null;
export function is_pending(template) {
if (template === ANON_VAR) {
return true;
} else if (is_place(template)) {
return true;
} else {
return false;
}
}
export function exec_deref(template) {
if (template === ANON_VAR) {
return template;
} else if (is_place(template)) {
let index = template.index;
let peek = temp_display[index];
if (peek === ANON_VAR) {
return template;
} else {
return deref(peek);
}
} else {
return deref(template);
}
}
/**************************************************************/
/* Albufeira Modes */
/**************************************************************/
export function exec_build(template) {
let back = null;
for (; ;) {
if (template === ANON_VAR) {
template = new Variable();
break;
} else if (is_place(template)) {
let index = template.index;
template = temp_display[index];
if (template === ANON_VAR) {
template = new Variable();
temp_display[index] = template;
} else {
template = deref(template);
}
break;
} else if (is_skeleton(template)) {
let args = new Array(template.args.length);
args[args.length - 1] = back;
back = new Compound(template.functor, args);
template = template.args;
let i = 0;
for (; i < args.length - 1; i++)
args[i] = exec_build(template[i]);
template = template[i];
} else {
template = deref(template);
break;
}
}
while (back !== null) {
let peek = back.args[back.args.length - 1];
back.args[back.args.length - 1] = template;
template = back;
back = peek;
}
return template;
}
export function exec_unify(template, alpha) {
for (; ;) {
if (template === ANON_VAR) {
return true;
} else if (is_place(template)) {
let index = template.index;
template = temp_display[index];
if (template === ANON_VAR) {
temp_display[index] = deref(alpha);
return true;
} else {
return unify(alpha, template);
}
} else if (is_skeleton(template)) {
alpha = deref(alpha);
if (is_variable(alpha)) {
let args = new Array(template.args.length);
bind(new Compound(template.functor, args), alpha);
template = template.args;
for (let i = 0; i < args.length; i++)
args[i] = exec_build(template[i]);
return true;
} else if (is_structure(alpha)) {
if (template.args.length !== alpha.args.length)
return false;
if (template.functor !== alpha.functor)
return false;
template = template.args;
alpha = alpha.args;
let i = 0;
for (; i < template.length - 1; i++)
if (!exec_unify(template[i], alpha[i]))
return false;
template = template[i];
alpha = 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.
*/
export function bind(source, term) {
term.instantiated = source;
term.tail = trail;
if (term instanceof Variable &&
(term.flags & VAR_MASK_STATE) === gc_mask)
term.flags |= VAR_MASK_STATE;
trail = term;
}
/**************************************************************/
/* Albufeira Clauses */
/**************************************************************/
export function exec_body(code, display, stop) {
temp_display = display;
let back = null;
let res = null;
for (let i = 0; i < code.length; i++) {
let goal = exec_build(code[i]);
let temp = new Compound(".", [goal, undefined]);
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;
}
export function exec_head(code, display, aux) {
if (aux.length !== code.length)
return false;
temp_display = display;
for (let 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 */
/**************************************************************/
export function exec_eval(template) {
if (template === ANON_VAR) {
throw make_error("instantiation_error");
} else if (is_place(template)) {
let index = template.index;
template = temp_display[index];
if (template === ANON_VAR)
throw make_error("instantiation_error");
}
template = deref(template);
if (is_number(template))
return template;
let peek = lookup_eval(template);
if (peek === undefined || (peek.flags & MASK_PRED_ARITH) === 0)
throw make_error(new Compound("type_error",
["evaluable", make_indicator_term(template)]));
if (is_structure(template)) {
template = template.args;
} else {
template = VOID_ARGS;
}
return peek.func(template);
}
function exec_test(template) {
let peek = lookup_pred(template);
if (peek !== undefined && (peek.flags & MASK_PRED_ROGUE) !== 0) {
let choice = exec_build(template.args[0]);
template = cutter(choice);
if (template === undefined) {
return true;
} else {
drain(redo.next);
return template;
}
} else if (peek === undefined || (peek.flags & MASK_PRED_TEST) === 0) {
return undefined;
} else {
if (is_structure(template)) {
template = template.args;
} else {
template = VOID_ARGS;
}
gc_enter++;
return peek.func(template);
}
}
export function exec_check(code, display) {
temp_display = display;
let i = 0;
let back = null;
let res = null;
for (;i < code.length; i++) {
let goal = exec_test(code[i]);
if (goal === undefined)
break;
if (goal === false) {
temp_display = null;
return false;
}
if (goal === true)
continue;
goal = new Compound(".", [goal, undefined]);
if (back === null) {
res = goal;
} else {
back.args[1] = goal;
}
back = goal;
break;
}
for (;i < code.length; i++) {
let goal = exec_build(code[i]);
goal = new Compound(".", [goal, undefined]);
if (back === null) {
res = goal;
} else {
back.args[1] = goal;
}
back = goal;
}
if (back === null) {
res = call.args[1];
} else {
back.args[1] = 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.
*/
export function unify(first, second) {
let stack = null;
let log = null;
try {
for (; ;) {
first = deref(first);
second = deref(second);
if (is_variable(first)) {
if (!is_variable(second) || first !== second)
bind(second, first);
} else if (is_variable(second)) {
bind(first, second);
} else if (!is_structure(first)) {
if (!Object.is(first, second))
break;
} else if (!is_structure(second)) {
break;
} else if (first.args.length !== second.args.length) {
break;
} else {
first = union_find(first);
second = union_find(second);
if (first !== second) {
if (is_frozen(first) && is_frozen(second) &&
first.hash !== second.hash)
break;
if (first.functor !== second.functor)
break;
log = union_add(log, first, second);
if (0 !== first.args.length - 1) {
let item2 = new Item(first, second, 0);
stack = stack_push(stack, item2);
}
first = first.args[0];
second = second.args[0];
continue;
}
}
let item = stack_peek(stack);
if (item === null) {
return true;
} else {
item.idx++;
first = item.first.args[item.idx];
second = item.second.args[item.idx];
if (item.idx === item.first.args.length - 1)
stack_pop(stack);
}
}
return false;
} finally {
union_undo(log);
}
}
/**************************************************************/
/* Engine */
/**************************************************************/
const SYS_MASK_STATE_ASYNC = 0x00000080;
/**
* Create a slow state engine.
*
* @constructor The engine.
*/
export function Engine() {
this.signal = undefined;
this.abort = () => {};
this.flags = SYS_MASK_STATE_ASYNC;
this.text_output = undefined;
this.text_error = undefined;
this.text_input = undefined;
this.low = 0;
this.high = 0;
this.serno = 0;
this.backtrail = null;
this.backredo = null;
this.partition = (stage === -1 ? "system" : "user");
this.done = null;
this.handlers = null;
}
export let engine = new Engine();
/**************************************************************/
/* Context */
/**************************************************************/
export const CTX_MAIN = "main";
export function Context() {
this.trail = null;
this.redo = null;
this.call = null;
this.gc_mask = VAR_MASK_ODD;
this.ref = new Engine();
this.ref.text_output = engine.text_output;
this.ref.text_error = engine.text_error;
this.ref.text_input = engine.text_input;
}
export let ctx = CTX_MAIN;
/**
* Set the task context.
*
* @param buf The context.
*/
export function ctx_set(buf) {
ctx = buf;
}
/**
* Switch the task context.
*
* @param buf The context.
*/
export function ctx_switch(buf) {
let temp = trail;
trail = buf.trail;
buf.trail = temp;
temp = redo;
redo = buf.redo;
buf.redo = temp;
temp = call;
call = buf.call;
buf.call = temp;
temp = gc_mask;
gc_mask = buf.gc_mask;
buf.gc_mask = temp;
temp = engine;
engine = buf.ref;
buf.ref = temp;
}
/**************************************************************/
/* 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.
* @throw If false.
*/
export function run(goal) {
if (!launch(goal, CTX_MAIN, VOID_ARGS))
throw make_error(new Compound("syntax_error", ["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 boolean True or false.
*/
export function launch(form, buf, paras) {
user_time -= real_time();
if (buf !== CTX_MAIN) {
ctx_set(buf);
ctx_switch(buf);
}
let back = engine.flags & SYS_MASK_FULL_ASYNC;
engine.flags &= ~SYS_MASK_FULL_ASYNC;
let snap = redo;
let mark = trail;
let stop = call;
call = melt_form(form, paras, stop);
let data = engine.handlers;
engine.handlers = null;
let found;
try {
for (; ; ) {
try {
found = solve(snap, stop, true);
break;
} catch (err) {
unwind_handlers(err);
}
}
} finally {
engine.handlers = data;
drain(snap);
unbind(mark);
call = stop;
engine.flags &= ~SYS_MASK_FULL_ASYNC;
engine.flags |= back;
if (buf !== CTX_MAIN) {
ctx_switch(buf);
ctx_set(CTX_MAIN);
}
user_time += real_time();
}
return found;
}
/**************************************************************/
/* 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.
*/
export async function launch_async(form, buf, paras) {
user_time -= real_time();
if (buf !== CTX_MAIN) {
ctx_set(buf);
ctx_switch(buf);
}
let back = engine.flags & SYS_MASK_FULL_ASYNC;
engine.flags |= SYS_MASK_FULL_ASYNC;
let snap = redo;
let mark = trail;
let stop = call;
call = melt_form(form, paras, stop);
let data = engine.handlers;
engine.handlers = null;
let found;
try {
for (;;) {
try {
found = solve(snap, stop, true);
if (found === false || found === true)
break;
if (buf !== CTX_MAIN) {
ctx_switch(buf);
ctx_set(CTX_MAIN);
}
user_time += real_time();
await found;
user_time -= real_time();
if (buf !== CTX_MAIN) {
ctx_set(buf);
ctx_switch(buf);
}
check_signal();
} catch (err) {
unwind_handlers(err);
}
}
} finally {
engine.handlers = data;
drain(snap);
unbind(mark);
call = stop;
engine.flags &= ~SYS_MASK_FULL_ASYNC;
engine.flags |= back;
if (buf !== CTX_MAIN) {
ctx_switch(buf);
ctx_set(CTX_MAIN);
}
user_time += real_time();
}
return found;
}
/**************************************************************/
/* Utilities */
/**************************************************************/
export function melt_form(form, paras, stop) {
if (is_clause(form)) {
let display = display_new(form.size);
if (exec_head(form.head, display, paras)) {
let peek = form.cutvar;
if (peek !== -1)
display[peek] = redo;
return exec_body(form.body, display, stop);
} else {
return stop;
}
} else if (is_goal(form)) {
let display = display_new(form.size);
let peek = form.cutvar;
if (peek !== -1)
display[peek] = redo;
return exec_body(form.body, display, stop);
} else {
return new Compound(".", [form, stop]);
}
}
export function determine_engine(buf) {
if (buf !== CTX_MAIN) {
if (buf !== ctx) {
return buf.ref;
} else {
return engine;
}
} else {
if (ctx !== CTX_MAIN) {
return ctx.ref;
} else {
return engine;
}
}
}