###
# 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.machine as machine
from nova.machine import (exec_deref, determine_engine,
is_pending, launch_async, launch, CTX_MAIN, for_later,
VOID_ARGS, is_special, exec_unify, exec_build, make_error)
from nova.store import (set, is_structure, check_nonvar,
Compound, is_variable, deref, copy_term)
from nova.special import (check_atom, check_integer, objects_list,
make_check, check_number, norm_float, narrow_float)
import nova.runtime as runtime
from nova.runtime import (
MASK_SRC_AREAD, Source, Sink,
map_stream_error)
import asyncio
import os
import sys
import calendar
import urllib.request
import urllib.error
import http.client
import time
import locale
import platform
import errno
import stat
################################################################
# Main API #
################################################################
###
# Post a message to the Prolog interpreter.
#
# @param msg The message.
##
def post(msg):
en = determine_engine(CTX_MAIN)
en.signal = msg
en.abort()
###
# Run a Prolog term once. The goal is run with auto-yield
# disabled and promises are not accepted.
#
# @param goal The Prolog term.
# @return True, false or yield.
##
def perform(goal):
return launch(goal, "main", VOID_ARGS)
###
# Run a Prolog term once. The goal is run with auto-yield
# enabled and promises are accepted.
#
# @param goal The Prolog term.
# @return True or false.
##
async def perform_async(goal):
return await launch_async(goal, "main", VOID_ARGS)
################################################################
# Register API #
################################################################
###
# The flag indicates a non-void dispatch foreign function.
##
FFI_FUNC = 0x00000100
###
# Add a Python function to the knowledge base. The given
# function is invoked with rather slow arguments spreading.
# Also the function is wrapped and registered as a
# special, therefore not eligible to neck optimization.
#
# @param functor The functor.
# @param arity The arity.
# @param func The Python function.
# @param flags The flags.
##
def register(functor, arity, func, flags):
if (flags & FFI_FUNC) != 0:
res = make_check(lambda args: invoke_func(func, args))
else:
res = make_check(lambda args: invoke(func, args))
set(functor, arity, res)
def invoke(func, args):
temp = [NotImplemented] * len(args)
i = 0
while i < len(temp):
temp[i] = exec_build(args[i])
i += 1
func(*temp)
return True
def invoke_func(func, args):
temp = [NotImplemented] * (len(args) - 1)
i = 0
while i < len(temp):
temp[i] = exec_build(args[i])
i += 1
res = func(*temp)
return exec_unify(args[len(args) - 1], res)
################################################################
# os_obj_new/1 and os_obj_current/3 #
################################################################
###
# os_obj_new(O):
# The predicate succeeds in O with a new Python object.
##
def test_os_obj_new(args):
res = {}
return exec_unify(args[0], res)
###
# os_obj_current(O, K, V):
# The predicate succeeds in V with the value of the key K
# in the Python object O.
##
def test_os_obj_current(args):
obj = exec_build(args[0])
key = exec_build(args[1])
check_atom(key)
if isinstance(obj, dict):
res = obj.get(key, NotImplemented)
else:
try:
res = getattr(obj, key, NotImplemented)
except AttributeError:
res = NotImplemented
if res is NotImplemented:
return False
return exec_unify(args[2], res)
################################################################
# os_obj_set/3, os_obj_reset/2 and os_obj_keys/2 #
################################################################
###
# os_obj_set(O, K, V):
# The predicate sets the value of the key K in the
# Python object O to V.
##
def test_os_obj_set(args):
obj = exec_build(args[0])
key = exec_build(args[1])
check_atom(key)
value = exec_build(args[2])
if isinstance(obj, dict):
obj[key] = value
else:
try:
setattr(obj, key, value)
except Exception:
raise make_error(Compound("permission_error",
["modify", "field", key]))
return True
###
# os_obj_reset(O, K):
# The predicate removes the key K from the Python object O.
##
def test_os_obj_reset(args):
obj = exec_build(args[0])
key = exec_build(args[1])
check_atom(key)
if isinstance(obj, dict):
if key in obj:
del obj[key]
else:
try:
if hasattr(obj, key):
delattr(obj, key)
except Exception:
raise make_error(Compound("permission_error",
["modify", "field", key]))
return True
###
# os_obj_keys(O, L):
# The predicate succeeds in L with the keys of
# the Python object O
##
def test_os_obj_keys(args):
obj = exec_build(args[0])
if isinstance(obj, dict):
obj = obj.keys()
else:
obj = dir(obj)
obj = set_to_list(obj)
return exec_unify(args[1], obj)
####
# Convert the keys of a native dict into a Prolog list.
#
# @param temp The native set.
##
def set_to_list(temp):
back = None
res = None
if temp is not None:
for peek in iter(temp):
peek = Compound(".", [peek, NotImplemented])
if back is None:
res = peek
else:
back.args[1] = peek
back = peek
if back is None:
res = "[]"
else:
back.args[1] = "[]"
return res
################################################################
# os_float_value/2 #
################################################################
###
# os_float_value(P, H):
# If P is instantiated, then the predicate succeeds in H with the
# Python float of P, otherwise in P with the Prolog float of H.
##
def test_os_float_value(args):
alpha = exec_deref(args[0])
if is_variable(alpha) or is_pending(alpha):
beta = exec_build(args[1])
check_number(beta)
res = beta if is_special(beta) else (
norm_float(narrow_float(beta)))
return exec_unify(alpha, res)
else:
alpha = exec_build(alpha)
check_number(alpha)
res = alpha if is_special(alpha) else (
narrow_float(alpha))
return exec_unify(args[1], res)
###
# os_atom_offset(A, P, H):
# If P is instantiated, then the predicate succeeds in H with
# the Python offset of P into atom A, otherwise in P with the
# Prolog offset of H into the atom A. If the corresponding
# offset exceeds the given atom A the predicate fails.
##
def test_os_atom_offset(args):
alpha = exec_build(args[0])
check_atom(alpha)
beta = exec_deref(args[1])
if is_variable(beta) or is_pending(beta):
gamma = exec_build(args[2])
check_integer(gamma)
if gamma < 0 or gamma > len(alpha):
return False
return exec_unify(beta, gamma)
else:
beta = exec_build(beta)
check_integer(beta)
if beta < 0 or beta > len(alpha):
return False
return exec_unify(args[2], beta)
###
# <p>Parse a date time string.</p>
#
# @param res The date time as a string.
# @param pat The pattern.
# @param utc The UTC calendar flag.
# @return The date time in UTC milliseconds.
##
def sys_time_parse(text, fmt, utc):
if utc != 0:
locale.setlocale(locale.LC_TIME, (None, None))
date = time.strptime(text, fmt)
return calendar.timegm(date)*1000
else:
locale.setlocale(locale.LC_TIME, locale.getlocale())
date = time.strptime(text, fmt)
return int(time.mktime(date)*1000)
################################################################
# os_get_gestalt/1 and os_get_host/1 #
################################################################
###
# os_get_gestalt(M): Internal only
# The built-in succeeds in M with a gestalt properties map.
##
def test_os_get_gestalt(args):
gestalt = {}
val = os.environ.get("TERM_SCHEME", None)
gestalt["sys_color"] = val if val is not None else "normal"
loc = locale.getlocale()[0]
gestalt["sys_locale"] = loc if loc is not None else ""
res = objects_list(sys.argv, 1, len(sys.argv)-1)
gestalt["argv"] = res
return exec_unify(args[0], gestalt)
###
# os_get_host(M): internal only
# The built-in succeeds in W with a host properties map.
##
def test_os_get_host(args):
res = {}
res["system_url"] = runtime.bootbase
res["foreign_ext"] = ".py"
res["host_info"] = (platform.python_implementation()+
", Python "+platform.python_version())
res["mach_info"] = (platform.machine()+
", "+platform.system())
return exec_unify(args[0], res)
################################################################
# os_get_workdir/1 and os_set_workdir/1 #
################################################################
###
# os_get_workdir(D): internal only
# The built-in succeeds in D with the working directory.
##
def test_os_get_workdir(args):
name = os.getcwd() + os.path.sep
return exec_unify(args[0], name)
###
# os_set_workdir(D): internal only
# The built-in succeeds. As a side effect it changes the working directory to D.
##
def test_os_set_workdir(args):
name = exec_build(args[0])
check_atom(name)
try:
os.chdir(name)
except OSError as err:
raise make_error(map_file_error(err, name))
return True
################################################################
# os_open_promise/4 #
################################################################
###
# os_open_promise(P, L, S, Q):
# The predicate succeeds in Q with a promise for open input S
# on path P and option list L.
##
def test_os_open_promise(args):
name = exec_build(args[0])
check_atom(name)
opts = exec_build(args[1])
stream = Source()
if not exec_unify(args[2], stream):
return False
return exec_unify(args[3], for_later(
open_file_promise(machine.engine, stream, name, opts)))
def get_encoding(opts):
if "encoding" in opts:
return opts["encoding"]
else:
return "utf8"
async def open_file_promise(en, stream, name, opts):
enc = get_encoding(opts)
try:
file = await asyncio.to_thread(open, name, encoding=enc, newline='')
except OSError as err:
en.signal = map_file_error(err, name)
return
stream.data = file
stream.receive = file_read_promise
stream.release = file_close_promise
stream.flags |= MASK_SRC_AREAD
async def file_read_promise(en, stream):
try:
res = await asyncio.to_thread(blocking_read, stream.data)
stream.buf = res
stream.pos = 0
except IOError as err:
en.signal = map_stream_error(err)
def blocking_read(data):
if data.fileno() == 0:
return data.readline(8192)
else:
return data.read(8192)
async def file_close_promise(en, stream):
try:
await asyncio.to_thread(blocking_close, stream.data)
except IOError as err:
en.signal = map_stream_error(err)
def blocking_close(data):
return data.close()
def map_file_error(err, name):
if err.errno == errno.ENOENT or err.errno == errno.ENOTDIR:
return Compound("existence_error", ["source_sink", name])
elif err.errno == errno.EISDIR or err.errno == errno.EACCES:
return Compound("permission_error",
["open", "source_sink", name])
else:
return Compound("resource_error", ["io_error"])
################################################################
# os_prop_promise/3 #
################################################################
###
# os_prop_promise(F, M, Q):
# The predicate succeeds in Q with with a promise for the
# properties M of the file F. Barks if path F doesn't exist
# or io exception while resolving.
##
def test_os_prop_promise(args):
name = exec_build(args[0])
check_atom(name)
res = {}
if not exec_unify(args[1], res):
return False
return exec_unify(args[2], for_later(
prop_file_promise(machine.engine, name, res)))
async def prop_file_promise(en, name, res):
try:
stats = await asyncio.to_thread(os.stat, name)
ftype = "regular" if stat.S_ISREG(stats.st_mode) else \
("directory" if stat.S_ISDIR(stats.st_mode) else "other")
res["type"] = ftype
res["absolute_path"] = os.path.abspath(name) + os.path.sep \
if ftype == "directory" else os.path.abspath(name)
res["last_modified"] = round(stats.st_mtime * 1000)
res["can_write"] = "true" \
if (stats.st_mode & stat.S_IWUSR) != 0 else "false"
except OSError as err:
if err.errno != errno.ENOENT and err.errno != errno.ENOTDIR:
en.signal = map_file_error(err, name)
################################################################
# os_open_sync/4 #
################################################################
###
# os_open_sync(P, M, L, S):
# The predicate succeeds. As a side effect the stream S is
# opened on the path P with the mode M and the option list L.
##
def test_os_open_sync(args):
name = exec_build(args[0])
check_atom(name)
mode = exec_build(args[1])
check_atom(mode)
opts = exec_build(args[2])
if "read" == mode:
raise make_error(Compound("resource_error",
["not_supported"]))
elif "write" == mode:
stream = open_write(name, "w", opts)
elif "append" == mode:
stream = open_write(name, "a", opts)
else:
raise make_error(Compound("domain_error",
["io_mode", mode]))
return exec_unify(args[3], stream)
def open_write(name, mode, opts):
enc = get_encoding(opts)
try:
file = open(name, mode, encoding=enc, newline='')
except OSError as err:
raise make_error(map_file_error(err, name))
dst = Sink()
dst.buf = ""
dst.data = file
dst.send = file_write
dst.release = file_close
return dst
def file_write(data, buf):
try:
data.write(buf)
return data
except IOError as err:
raise make_error(map_stream_error(err))
def file_close(data):
try:
data.close()
except IOError as err:
raise make_error(map_stream_error(err))
################################################################
# os_cntrl_sync/2 and os_read_sync/1 #
################################################################
###
# os_cntrl_sync(F, P):
# The predicate assigns the property P to the file F.
##
def test_os_cntrl_sync(args):
name = exec_build(args[0])
check_atom(name)
prop = exec_build(args[1])
if (is_structure(prop) and
prop.functor == "last_modified"
and len(prop.args) == 1):
val = deref(prop.args[0])
check_integer(val)
if val < 0:
raise make_error(Compound("domain_error",
["not_less_than_zero", val]))
try:
os.utime(name, (val/1000, val/1000))
except OSError as err:
raise make_error(map_file_error(err, name))
elif (is_structure(prop) and
prop.functor == "can_write"
and len(prop.args) == 1):
val = deref(prop.args[0])
check_atom(val)
if "true" != val and "false" != val:
raise make_error(Compound("domain_error",
["boolean", val]))
try:
stats = os.stat(name)
if "true" == val:
os.chmod(name, (stats.st_mode | 0x80))
else:
os.chmod(name, (stats.st_mode & ~0x80))
except OSError as err:
raise make_error(map_file_error(err, name))
else:
check_nonvar(prop)
prop = copy_term(prop)
raise make_error(Compound("domain_error",
["file_property", prop]))
return True
################################################################
# os_http_open_promise/4 #
################################################################
###
# os_http_open_promise(P, L, S, Q):
# The predicate succeeds in Q with a promise for open input S
# on path P and option list L.
##
def test_os_http_open_promise(args):
url = exec_build(args[0])
check_atom(url)
opts = exec_build(args[1])
stream = Source()
if not exec_unify(args[2], stream):
return False
return exec_unify(args[3], for_later(
open_http_promise(machine.engine, stream, url, opts)))
async def open_http_promise(en, stream, url, opts):
if "method" in opts:
method = opts["method"]
elif "body" in opts:
method = "POST"
else:
method = "GET"
if "body" in opts:
opts2 = opts["body"]
enc = get_encoding(opts2)
body = opts2["text"].encode(enc)
else:
body = None
if "headers" in opts:
headers = opts["headers"]
else:
headers = {}
request = urllib.request.Request(url,
data=body, headers=headers, method=method)
try:
response = await asyncio.to_thread(urllib.request.urlopen, request)
except http.client.RemoteDisconnected as err:
en.signal = map_stream_error(err)
return
except urllib.error.HTTPError as err:
en.signal = map_http_result(err, url)
return
except urllib.error.URLError as err:
en.signal = map_net_error(err, url)
return
opts["uri"] = response.url
opts["status"] = response.status
res = {}
vmap = response.headers
for key in vmap:
res[key.lower()] = vmap[key]
opts["fields"] = res
enc = get_encoding(opts)
stream.data = response
stream.receive = lambda en, stream: http_read_promise(enc, en, stream)
stream.release = file_close_promise
stream.flags |= MASK_SRC_AREAD
async def http_read_promise(enc, en, stream):
try:
res = await asyncio.to_thread(blocking_chunk, enc, stream.data)
stream.buf = res
stream.pos = 0
except IOError as err:
en.signal = map_stream_error(err)
def blocking_chunk(enc, data):
return data.read().decode(enc)
def map_net_error(err, url):
code = err.reason.errno if hasattr(err, 'reason') else 0
if code == 11001:
return Compound("existence_error", ["host", url])
elif code == 10060:
return Compound("resource_error", ["connect_failed"])
else:
return Compound("resource_error", ["remote_error"])
def map_http_result(err, url):
code = err.code
if code == 403: # Forbidden
return Compound("permission_error",
["open", "source_sink", url])
elif code == 404: # Not Found
return Compound("existence_error",
["source_sink", url])
elif code == 405: # Method Not Allowed
return Compound("resource_error",
["illegal_method"])
elif code == 500: # Internal Server Error
return Compound("resource_error",
["internal_error"])
elif code == 503: # Service Unavailable
return Compound("resource_error",
["service_unavailable"])
else:
return Compound("resource_error",
["io_exception"])
################################################################
# os_http_prop_promise/3 #
################################################################
HTTP_TIME = "%a, %d %b %Y %H:%M:%S GMT"
##
# os_http_prop_promise(F, M, Q):
# The predicate succeeds in Q with with a promise for the
# properties M of the file F. Barks if path F doesn't exist
# or io exception while resolving.
##
def test_os_http_prop_promise(args):
url = exec_build(args[0])
check_atom(url)
res = {}
if not exec_unify(args[1], res):
return False
return exec_unify(args[2], for_later(
prop_http_promise(machine.engine, url, res)))
async def prop_http_promise(en, url, res):
request = urllib.request.Request(url, method="HEAD")
try:
response = await asyncio.to_thread(urllib.request.urlopen, request)
await asyncio.to_thread(response.close)
except http.client.RemoteDisconnected as err:
en.signal = map_stream_error(err)
return
except urllib.error.HTTPError as err:
if err.code != 404:
en.signal = map_http_result(err, url)
return
except urllib.error.URLError as err:
en.signal = map_net_error(err, url)
return
val = response.headers.get("last-modified")
mtime = sys_time_parse(val, HTTP_TIME, 1) \
if val is not None else -1
res["last_modified"] = mtime
res["absolute_path"] = response.url
res["type"] = "regular"
res["can_write"] = "false"
################################################################
# os_http_open_sync/4 and os_http_cntrl_sync/2 #
################################################################
###
# os_http_open_sync(P, M, L, S):
# The predicate succeeds. As a side effect the stream S is
# opened on the path P with the mode M and the option list L.
##
def test_os_http_open_sync(args):
url = exec_build(args[0])
check_atom(url)
raise make_error(Compound("permission_error",
["access", "source_sink", url]))
###
# os_http_cntrl_sync(F, P):
# The predicate assigns the property P to the file F.
##
def test_os_http_cntrl_sync(args):
url = exec_build(args[0])
check_atom(url)
raise make_error(Compound("permission_error",
["access", "source_sink", url]))
################################################################
# Theatre Init #
################################################################
# system specials, host
set("os_obj_new", 1, make_check(test_os_obj_new))
set("os_obj_current", 3, make_check(test_os_obj_current))
set("os_obj_set", 3, make_check(test_os_obj_set))
set("os_obj_reset", 2, make_check(test_os_obj_reset))
set("os_obj_keys", 2, make_check(test_os_obj_keys))
# system specials, types
set("os_float_value", 2, make_check(test_os_float_value))
set("os_atom_offset", 3, make_check(test_os_atom_offset))
# stream specials, gestalt
set("os_get_gestalt", 1, make_check(test_os_get_gestalt))
set("os_get_host", 1, make_check(test_os_get_host))
set("os_get_workdir", 1, make_check(test_os_get_workdir))
set("os_set_workdir", 1, make_check(test_os_set_workdir))
# stream specials, file
set("os_open_promise", 4, make_check(test_os_open_promise))
set("os_prop_promise", 3, make_check(test_os_prop_promise))
set("os_open_sync", 4, make_check(test_os_open_sync))
set("os_cntrl_sync", 2, make_check(test_os_cntrl_sync))
# stream specials, net
set("os_http_open_promise", 4, make_check(test_os_http_open_promise))
set("os_http_prop_promise", 3, make_check(test_os_http_prop_promise))
set("os_http_open_sync", 4, make_check(test_os_http_open_sync))
set("os_http_cntrl_sync", 2, make_check(test_os_http_cntrl_sync))