Python "machine"

         
###
# 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 nova.store as store
from nova.store import (is_logical, is_clause, Undo,
resolve_link, snapshot_peek, pred_link, ANON_VAR,
MASK_PRED_ARITH, MASK_PRED_TEST, MASK_PRED_ROGUE,
MASK_PRED_SPECIAL, is_goal, stack_peek, is_quote, Item,
stack_pop, stack_push, deref, is_compound, is_place,
union_add, union_find, union_undo, is_frozen,
VAR_MASK_ODD, VAR_MASK_STATE, VAR_MASK_SERNO,
snapshot_rope, defined_pred, is_stick,
Variable, is_variable, site_name,
Compound, is_structure, is_skeleton)
import time
import asyncio
import platform
import struct
import math
import numbers
import gc
import os
VOID_ARGS = []
trail = None
redo = None
call = None
###
# Create an error term from a message.
#
# @param beta The message.
# @return The error term.
##
def make_error(beta):
return Exception(Compound("error", [beta, fetch_stack(ctx)]))
###
# Create a new display array.
#
# @param size The size.
# @return The display array or None.
##
def display_new(size):
if size == 0:
return None
else:
display = [ANON_VAR] * size
return display
###
# Retrieve the current stack.
#
# @param buf The context.
# @return The current stack.
##
def fetch_stack(buf):
temp = pred_link("sys_including", 3)
if (temp is NotImplemented or (not is_logical(temp.func) and
not is_stick(temp.func))):
return "[]"
data = snapshot_peek(temp.func)
back = None
res = None
i = 0
while i < len(data):
clause = data[i]
display = display_new(clause.size)
alpha = exec_frame("sys_including", clause.head, display)
if not object_equals(alpha.args[1], buf):
i += 1
continue
alpha = fetch_frame(alpha)
alpha = Compound(".", [alpha, NotImplemented])
if back is None:
res = alpha
else:
back.args[1] = alpha
back = alpha
i += 1
if back is None:
res = "[]"
else:
back.args[1] = "[]"
return res
def exec_frame(functor, head, display):
global temp_display
if len(head) > 0:
temp_display = display
args = [NotImplemented] * len(head)
i = 0
while i < len(args):
args[i] = exec_build(head[i])
i += 1
temp_display = None
return Compound(functor, args)
else:
return functor
def fetch_frame(alpha):
file = alpha.args[0]
k1 = file.rfind('/')
k2 = file.rfind('\\')
name = file[max(k1, k2) + 1:]
stream = alpha.args[2]
return 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.
##
def make_indicator(functor, arity):
return Compound("/", [site_name(functor), arity])
def object_hash_code(alpha):
if is_atom(alpha):
res = 0
i = 0
while i < len(alpha):
res = int32(res * 31 + ord(alpha[i]))
i += 1
return res
elif is_number(alpha):
if is_integer(alpha):
if -0x8000000 <= alpha <= 0x7FFFFFFF:
return alpha
else:
if alpha < 0:
sign = -1
alpha = -alpha
else:
sign = 1
alpha = "%x" % alpha
res = 0
i = len(alpha) % 8
if i > 0:
res = int32(int(alpha[0:i], 16))
while i < len(alpha):
res = int32(res * 31 + int(alpha[i:i+8], 16))
i += 8
return res if sign > 0 else -res
else:
beta = struct.pack(">d", alpha)
gamma = struct.unpack(">l", beta[0:4]) + struct.unpack(">l", beta[4:8])
return gamma[0] ^ gamma[1]
elif alpha is None:
return 0
elif alpha is True:
return 1231
elif alpha is False:
return 1237
else:
return 2467
def int32(alpha):
alpha &= 0xFFFFFFFF
if alpha >= 0x80000000:
return alpha - 0x100000000
else:
return alpha
################################################################
# Garbage Collection #
################################################################
###
# Retrieve the real time.
#
# @return The real time.
##
def real_time():
return time.monotonic_ns() / 1000000.0
###
# Retrieve the used memory.
#
# @return The used memory, or zero.
##
def used_memory():
if platform.python_implementation() == "PyPy":
stats = gc._get_stats()
return (stats.total_gc_memory+
stats.total_memory_pressure+
stats.jit_backend_used)
else:
return 0
###
# Retrieve the max memory.
#
# @return The max memory, or zero.
##
def max_memory():
if platform.python_implementation() == "PyPy":
maxstr = os.environ.get("PYPY_GC_MAX", None)
if maxstr is None:
return 0
maxstr = maxstr.upper()
if maxstr.endswith("B"):
maxstr = maxstr[:-1]
i = 0
mult = 1
while i < 3:
if maxstr.endswith("KMG"[i]):
mult = 1024**(i+1)
maxstr = maxstr[:-1]
break
i += 1
return int(float(maxstr)*mult)
else:
return 0
gc_time = 0.0
user_time = 0.0
gc_last = 0.0
gc_maxinfs = 144000 if platform.python_implementation() == "PyPy" else 88000
gc_mask = VAR_MASK_ODD
gc_enter = 0
gc_tick = gc_maxinfs
gc_tack = 60*gc_maxinfs
gc_tock = 3600*gc_maxinfs
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
##
def gc_run():
global gc_tock
global gc_time
global gc_maxinfs
global gc_last
gc_time -= real_time()
if gc_enter >= gc_tock:
gc_major()
gc_tock += 3600*gc_maxinfs
elif (gc_maxmem != 0 and
used_memory() > gc_maxmem * 3 / 4):
gc_major()
gc_tock += 60*gc_maxinfs
else:
gc_minor()
val = real_time()
gc_time += val
val = user_time + val
val2 = val - gc_last
gc_last = val
val2 = (gc_maxinfs * 1000) / val2
gc_maxinfs = round((3*gc_maxinfs + val2) / 4)
###
# Perform major garbage collection.
##
def gc_major():
global gc_mask
gc_mask ^= VAR_MASK_STATE
engine.low = 0
engine.high = engine.serno
engine.serno = 0
mark_redo(None, True)
mark_trail(None, True)
adjust_redo(None)
sweep_trail(None)
###
# Perform minor garbage collection.
##
def 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 term The term.
# @param scan The serno scanning flag.
##
def mark_term(first, scan):
stack = None
while True:
if is_variable(first):
if (first.flags & VAR_MASK_STATE) != gc_mask:
first.flags = (first.flags & ~VAR_MASK_STATE) | gc_mask
if scan:
val = first.flags & VAR_MASK_SERNO
if val != VAR_MASK_SERNO:
if val > engine.serno:
engine.serno = val + 1
if engine.low <= val and val < engine.high:
if val - engine.low > engine.high - val:
engine.high = val
else:
engine.low = val + 1
if first.instantiated is not NotImplemented:
peek = first.instantiated
first.instantiated = stack
stack = first
first = peek
continue
elif is_compound(first):
if (first.walk & VAR_MASK_STATE) != gc_mask:
first.walk = (first.walk & ~VAR_MASK_STATE) | gc_mask
peek = first.args[0]
first.args[0] = stack
first.walk &= ~VAR_MASK_SERNO
stack = first
first = peek
continue
while (stack is not None and (is_variable(stack) or
(stack.walk & VAR_MASK_SERNO) == len(stack.args) - 1)):
if is_variable(stack):
peek = stack.instantiated
stack.instantiated = first
first = stack
stack = peek
else:
peek = stack.args[stack.walk & VAR_MASK_SERNO]
stack.args[stack.walk & VAR_MASK_SERNO] = first
first = stack
stack = peek
if stack is None:
return
else:
peek = stack.args[stack.walk & VAR_MASK_SERNO]
stack.args[stack.walk & VAR_MASK_SERNO] = first
stack.walk += 1
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.
##
def mark_redo(snap, scan):
mark_term(call, scan)
last = redo
while last is not snap:
mark_term(last.cont, scan)
last = last.next
###
# Mark the trail
#
# @param stop The stop.
# @param scan The serno scanning flag.
##
def mark_trail(stop, scan):
temp = trail
while temp is not stop:
if (not scan and isinstance(temp,Variable) and
(temp.flags & VAR_MASK_STATE) == VAR_MASK_STATE):
mark_term(temp, False)
elif isinstance(temp,Undo):
mark_term(temp.instantiated, scan)
temp = temp.tail
################################################################
# Variable Sweep #
################################################################
###
# Adjust the markers into the trail.
#
# @param snap The snap.
##
def adjust_redo(snap):
last = redo
while last is not snap:
temp = last.mark
while temp is not None:
if (isinstance(temp,Variable) and
(temp.flags & VAR_MASK_STATE) == gc_mask):
break
elif isinstance(temp,Undo):
break
else:
temp = temp.tail
last.mark = temp
last = last.next
engine.backredo = redo
###
# Sweep the trail.
#
# @param stop The stop.
##
def sweep_trail(stop):
global trail
temp = trail
back = None
while temp is not stop:
term = temp
temp = term.tail
if (isinstance(term,Variable) and
(term.flags & VAR_MASK_STATE) == gc_mask):
if back is not None:
back.tail = term
else:
trail = term
back = term
elif isinstance(term,Undo):
if back is not None:
back.tail = term
else:
trail = term
back = term
else:
term.instantiated = NotImplemented
term.tail = None
if back is not None:
back.tail = stop
else:
trail = stop
engine.backtrail = trail
################################################################
# Clause Loops #
################################################################
SYS_MASK_ASYNC_MODE = 0x00000001
SYS_MASK_ALLOW_YIELD = 0x00000008
SYS_MASK_FULL_ASYNC = SYS_MASK_ASYNC_MODE | SYS_MASK_ALLOW_YIELD
###
# Set the continuation.
#
# @param term The continuation.
##
def cont(term):
global call
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.
##
def solve(snap, stop, found):
global call
global redo
global gc_enter
global gc_tick
global gc_tack
while True:
if found is 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 for_later(immediate_promise())
if call is not stop:
gc_enter += 1
goal = call.args[0]
peek = lookup_pred(goal)
if peek is NotImplemented or (peek.flags & MASK_PRED_ARITH) != 0:
raise make_error(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 not peek.func(goal):
found = False
else:
call = call.args[1]
found = True
elif (peek.flags & MASK_PRED_SPECIAL) != 0:
found = peek.func(goal)
else:
peek = defined_pred(peek, goal)
found = solve2_rope(goal, snapshot_rope(peek), 0, None)
else:
break
elif found is False:
if redo is not snap:
choice = redo
goal = release(choice.mark)
if goal is NotImplemented:
drain(choice.next)
call = choice.cont
found = choice.func(choice.data, choice.at, choice)
else:
found = Compound(".", ["fail", call])
call = Compound(".", [goal, found])
found = True
else:
break
else:
break
return found
async def immediate_promise():
try:
await asyncio.sleep(0)
except asyncio.CancelledError:
pass
###
# Release variable bindings.
#
# @param mark The trail mark.
##
def unbind(mark):
global trail
while mark is not trail:
temp = trail
trail = temp.tail
if engine.backtrail is temp:
engine.backtrail = trail
temp.instantiated = NotImplemented
temp.tail = None
###
# Release variable bindings or find a undo goal.
#
# @param mark The trail mark.
# @return Undefined if release completed, otherwise the undo goal.
##
def release(mark):
global trail
while mark is not trail:
temp = trail
trail = temp.tail
if engine.backtrail is temp:
engine.backtrail = trail
if isinstance(temp,Undo):
goal = temp.instantiated
temp.instantiated = NotImplemented
temp.tail = None
return goal
else:
temp.instantiated = NotImplemented
temp.tail = None
return NotImplemented
################################################################
# Signal Handling #
################################################################
###
# Check and throw the signal message.
##
def check_signal():
if engine.signal is NotImplemented:
return True
msg = engine.signal
engine.signal = NotImplemented
msg = melt_quote(msg)
raise make_error(msg)
def melt_quote(first):
global temp_display
if is_quote(first):
temp_display = display_new(first.size)
res = exec_build(first.skel)
temp_display = None
return res
else:
return first
def unwind_handlers(err):
global call
global redo
err = map_throwable(err)
found = stack_peek(engine.handlers)
while found is not None:
peek = cutter(found)
goal = release(redo.mark)
if goal is not NotImplemented:
found = Compound("os_raise", [err.args[0]])
found = Compound(".", [found, call])
call = Compound(".", [goal, found])
return
if peek is not NotImplemented:
drain(redo.next)
found = Compound("os_raise", [err.args[0]])
found = Compound(".", [found, call])
call = 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.args[0]):
break
elif "shield" == peek:
engine.flags |= SYS_MASK_ASYNC_MODE
elif "unshield" == peek:
engine.flags &= ~SYS_MASK_ASYNC_MODE
else:
raise Exception("illegal handler")
found = stack_peek(engine.handlers)
if found is None:
raise err
else:
found = deref(found.args[2])
call = Compound(".", [found, call])
def map_throwable(err):
if isinstance(err, RecursionError):
err = make_error(Compound("system_error", ["stack_overflow"]))
elif isinstance(err, MemoryError):
err = make_error(Compound("system_error", ["out_of_memory"]))
return err
###
# Cut to the choice point.
#
# @param choice The choice point mark.
##
def drain(choice):
global redo
while choice is not redo:
temp = redo
redo = temp.next
if engine.backredo is 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.
##
def cutter(choice):
global redo
while choice is not redo:
temp = redo
peek = temp.cont
peek = peek.args[0]
if (is_structure(peek) and
"sys_cleanup" == site_name(peek.functor) and
len(peek.args) == 1):
return deref(peek.args[0])
redo = temp.next
if engine.backredo is temp:
engine.backredo = redo
return NotImplemented
################################################################
# Linked Provables #
################################################################
###
# Lookup a predicate.
#
# @param goal The goal.
# @return The predicate or NotImplemented
##
def lookup_pred(goal):
if is_structure(goal):
functor = goal.functor
arity = len(goal.args)
else:
functor = goal
arity = 0
return resolve_link(functor, arity)
###
# Lookup an evaluable function.
#
# @param expr The arithmetic expression.
# @return The evaluable function or NotImplemented
##
def lookup_eval(expr):
if is_structure(expr):
functor = expr.functor
arity = len(expr.args)
else:
functor = expr
arity = 0
return resolve_link(functor, arity + 1)
def make_indicator_term(goal):
if is_structure(goal):
functor = goal.functor
arity = len(goal.args)
else:
functor = goal
arity = 0
return make_indicator(functor, arity)
def solve_rope(rope, at, choice):
goal = deref(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 clausse list.
# @param at The clause index.
# @param choice The choice point for reuse or None.
# @return True if search succeeds, otherwise false.
##
def solve2_rope(paras, rope, at, choice):
global redo
mark = trail
while at < len(rope):
clause = rope[at]
at += 1
display = display_new(clause.size)
if exec_head(clause.head, display, paras):
peek = clause.cutvar
if peek != -1:
display[peek] = redo
if at < len(rope):
if choice is None:
choice = Choice(solve_rope, rope, at, mark)
else:
choice.at = at
redo = choice
if exec_check(clause.body, display):
return True
if redo is not 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.
##
def more(choice):
global redo
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.
##
class Choice:
def __init__(self, func, data, at, mark):
self.func = func
self.data = data
self.at = at
self.mark = mark
self.cont = call
self.next = redo
################################################################
# Terms #
################################################################
###
# Check whether an object is an atom.
#
# @param obj The object.
# @return True if the object is an atom, otherwise false.
##
def is_atom(obj):
return isinstance(obj, str)
###
# Check whether an object is a number.
#
# @param obj The object.
# @return True if the object is a number, otherwise false.
##
def is_number(obj):
return isinstance(obj, numbers.Number) and not isinstance(obj, bool)
###
# Check whether an object is an integer.
#
# @param obj The object.
# @return True if the object is an integer, otherwise false.
##
def is_integer(obj):
return isinstance(obj, int) and not isinstance(obj, bool)
###
# Check whether an object is a float.
#
# @param obj The object.
# @return True if the object is a float, otherwise false.
##
def is_float(obj):
return isinstance(obj, float)
###
# Check whether an object is a special value.
#
# @param alpha The object.
# @return boolean True if the object is a special value, otherwise false.
##
def is_special(alpha):
return (isinstance(alpha, float) and
not math.isfinite(alpha))
################################################################
# Albufeira Lazy #
################################################################
temp_display: (list | None) = None
def is_pending(template):
if template is ANON_VAR:
return True
elif is_place(template):
return True
else:
return False
def exec_deref(template):
if template is ANON_VAR:
return template
elif is_place(template):
index = template.index
peek = temp_display[index]
if peek is ANON_VAR:
return template
else:
return deref(peek)
else:
return deref(template)
################################################################
# Albufeira Modes #
################################################################
def exec_build(template):
back = None
while True:
if template is ANON_VAR:
template = Variable()
break
elif is_place(template):
index = template.index
template = temp_display[index]
if template is ANON_VAR:
template = Variable()
temp_display[index] = template
else:
template = deref(template)
break
elif is_skeleton(template):
args = [NotImplemented] * len(template.args)
args[len(args)-1] = back
back = Compound(template.functor, args)
template = template.args
i = 0
while i < len(args) - 1:
args[i] = exec_build(template[i])
i += 1
template = template[i]
else:
template = deref(template)
break
while back is not None:
peek = back.args[len(back.args) - 1]
back.args[len(back.args) - 1] = template
template = back
back = peek
return template
def exec_unify(template, alpha):
while True:
if template is ANON_VAR:
return True
elif is_place(template):
index = template.index
template = temp_display[index]
if template is ANON_VAR:
temp_display[index] = deref(alpha)
return True
else:
return unify(alpha, template)
elif is_skeleton(template):
alpha = deref(alpha)
if is_variable(alpha):
args = [NotImplemented] * len(template.args)
bind(Compound(template.functor, args), alpha)
template = template.args
i = 0
while i < len(args):
args[i] = exec_build(template[i])
i += 1
return True
elif is_structure(alpha):
if len(template.args) != len(alpha.args):
return False
if not object_equals(template.functor, alpha.functor):
return False
template = template.args
alpha = alpha.args
i = 0
while i < len(template) - 1:
if not exec_unify(template[i], alpha[i]):
return False
i += 1
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.
##
def bind(source, term):
global trail
term.instantiated = source
term.tail = trail
if (isinstance(term,Variable) and
(term.flags & VAR_MASK_STATE) == gc_mask):
term.flags |= VAR_MASK_STATE
trail = term
################################################################
# Albufeira Clauses #
################################################################
def exec_body(code, display, stop):
global temp_display
temp_display = display
back = None
res = None
i = 0
while i < len(code):
goal = exec_build(code[i])
temp = Compound(".", [goal, NotImplemented])
if back is None:
res = temp
else:
back.args[1] = temp
back = temp
i += 1
if back is None:
res = stop
else:
back.args[1] = stop
temp_display = None
return res
def exec_head(code, display, aux):
global temp_display
if len(aux) != len(code):
return False
temp_display = display
i = 0
while i < len(code):
if not exec_unify(code[i], aux[i]):
temp_display = None
return False
i += 1
temp_display = None
return True
################################################################
# Head Check #
################################################################
def exec_eval(template):
if template is ANON_VAR:
raise make_error("instantiation_error")
elif is_place(template):
index = template.index
template = temp_display[index]
if template is ANON_VAR:
raise make_error("instantiation_error")
template = deref(template)
if is_number(template):
return template
peek = lookup_eval(template)
if peek is NotImplemented or (peek.flags & MASK_PRED_ARITH) == 0:
raise make_error(Compound("type_error",
["evaluable", make_indicator_term(template)]))
if is_structure(template):
template = template.args
else:
template = VOID_ARGS
return peek.func(template)
def exec_test(template):
global redo
global gc_enter
peek = lookup_pred(template)
if peek is not NotImplemented and (peek.flags & MASK_PRED_ROGUE) != 0:
choice = exec_build(template.args[0])
template = cutter(choice)
if template is NotImplemented:
return True
else:
drain(redo.next)
return template
elif peek is NotImplemented or (peek.flags & MASK_PRED_TEST) == 0:
return NotImplemented
else:
if is_structure(template):
template = template.args
else:
template = VOID_ARGS
gc_enter += 1
return peek.func(template)
def exec_check(code, display):
global temp_display
global call
temp_display = display
i = 0
back = None
res = None
while i < len(code):
goal = exec_test(code[i])
if goal is NotImplemented:
break
if goal is False:
temp_display = None
return False
if goal is True:
i += 1
continue
goal = Compound(".", [goal, NotImplemented])
if back is None:
res = goal
else:
back.args[1] = goal
back = goal
break
while i < len(code):
goal = exec_build(code[i])
goal = Compound(".", [goal, NotImplemented])
if back is None:
res = goal
else:
back.args[1] = goal
back = goal
i += 1
if back is None:
res = call.args[1]
else:
back.args[1] = call.args[1]
temp_display = None
call = res
return True
################################################################
# Object Equals #
################################################################
###
# Determine whether two objects are equal.
#
# @param alpha The first object.
# @param beta The second object.
##
def object_equals(alpha, beta):
if is_atom(alpha) or is_number(alpha):
if is_float(alpha):
return (is_float(beta) and
(math.isnan(beta) if math.isnan(alpha) else alpha == beta))
elif is_float(beta):
return False
else:
return alpha == beta
elif is_atom(beta) or is_number(beta):
return False
else:
return alpha is beta
################################################################
# 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 True if the two terms unify, otherwise false.
##
def unify(first, second):
stack = None
log = None
try:
while True:
first = deref(first)
second = deref(second)
if is_variable(first):
if not is_variable(second) or first is not second:
bind(second, first)
elif is_variable(second):
bind(first, second)
elif not is_structure(first):
if not object_equals(first, second):
break
elif not is_structure(second):
break
elif len(first.args) != len(second.args):
break
else:
first = union_find(first)
second = union_find(second)
if first is not second:
if (is_frozen(first) and is_frozen(second) and
first.hash != second.hash):
break
if not object_equals(first.functor, second.functor):
break
log = union_add(log, first, second)
if 0 != len(first.args) - 1:
item2 = Item(first, second, 0)
stack = stack_push(stack, item2)
first = first.args[0]
second = second.args[0]
continue
item = stack_peek(stack)
if item is None:
return True
else:
item.idx += 1
first = item.first.args[item.idx]
second = item.second.args[item.idx]
if item.idx == len(item.first.args) - 1:
stack_pop(stack)
return False
finally:
union_undo(log)
################################################################
# Engine #
################################################################
###
# Create a slow state engine.
#
# @constructor The engine.
##
class Engine:
def __init__(self):
self.signal = NotImplemented
self.abort = lambda: None
self.flags = 0
self.text_output = NotImplemented
self.text_error = NotImplemented
self.text_input = NotImplemented
self.low = 0
self.high = 0
self.serno = 0
self.backtrail = None
self.backredo = None
self.partition = "system" if store.stage == -1 else "user"
self.done = None
self.handlers = None
engine = Engine()
################################################################
# Context #
################################################################
CTX_MAIN = "main"
###
# Create a task context.
#
# @param goal The list of goals.
# @constructor The task context.
##
class Context:
def __init__(self):
self.trail = None
self.redo = None
self.call = None
self.gc_mask = VAR_MASK_ODD
self.ref = Engine()
self.ref.text_output = engine.text_output
self.ref.text_error = engine.text_error
self.ref.text_input = engine.text_input
ctx = CTX_MAIN
###
# Set the task context.
#
# @param buf The task context.
##
def ctx_set(buf):
global ctx
ctx = buf
###
# Switch the task context.
#
# @param buf The context.
##
def ctx_switch(buf):
global trail
global redo
global call
global gc_mask
global engine
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.
##
def run(goal):
if not launch(goal, CTX_MAIN, VOID_ARGS):
raise make_error(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 True or false.
##
def launch(form, buf, paras):
global user_time
global call
user_time -= real_time()
if buf != CTX_MAIN:
ctx_set(buf)
ctx_switch(buf)
back = engine.flags & SYS_MASK_FULL_ASYNC
engine.flags &= ~SYS_MASK_FULL_ASYNC
snap = redo
mark = trail
stop = call
call = melt_form(form, paras, stop)
data = engine.handlers
engine.handlers = None
try:
while True:
try:
found = solve(snap, stop, True)
break
except BaseException as 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 #
################################################################
###
# Pack a coro.
#
# @param The coro
# @return The packed coro
##
def for_later(coro):
return lambda : coro
###
# 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.
##
async def launch_async(form, buf, paras):
global user_time
global call
user_time -= real_time()
if buf != CTX_MAIN:
ctx_set(buf)
ctx_switch(buf)
back = engine.flags & SYS_MASK_FULL_ASYNC
engine.flags |= SYS_MASK_FULL_ASYNC
snap = redo
mark = trail
stop = call
call = melt_form(form, paras, stop)
data = engine.handlers
engine.handlers = None
try:
while True:
try:
found = solve(snap, stop, True)
if found is False or found is 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()
except BaseException as 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 #
################################################################
def melt_form(form, paras, stop):
if is_clause(form):
display = display_new(form.size)
if exec_head(form.head, display, paras):
peek = form.cutvar
if peek != -1:
display[peek] = redo
return exec_body(form.body, display, stop)
else:
return stop
elif is_goal(form):
display = display_new(form.size)
peek = form.cutvar
if peek != -1:
display[peek] = redo
return exec_body(form.body, display, stop)
else:
return Compound(".", [form, stop])
def determine_engine(buf):
if buf != CTX_MAIN:
if buf is not ctx:
return buf.ref
else:
return engine
else:
if ctx != CTX_MAIN:
return ctx.ref
else:
return engine