This commit is contained in:
Vitor Santos Costa 2017-06-22 10:41:41 +01:00
parent d7e21c80df
commit 9272a1c7d5
6 changed files with 109 additions and 62 deletions

View File

@ -603,14 +603,19 @@ Term YAPEngine::fun(Term t)
// don't forget, on success these guys may create slots // don't forget, on success these guys may create slots
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec "); __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec ");
if (YAP_EnterGoal(ap, nullptr, &q) == 0) if (YAP_EnterGoal(ap, nullptr, &q) == 0) {
#if DEBUG
fprintf(stderr,"function call failed:\n");
#endif
return 0; return 0;
XREGS[arity] = Yap_GetFromSlot(o); }
DBTerm *pt = Yap_StoreTermInDB(Yap_GetFromSlot(o), arity);
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "out %ld", o); __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "out %ld", o);
YAP_LeaveGoal(false, &q); YAP_LeaveGoal(false, &q);
Yap_CloseHandles(q.CurSlot); Yap_CloseHandles(q.CurSlot);
Term rc = Yap_PopTermFromDB(pt);
RECOVER_MACHINE_REGS(); RECOVER_MACHINE_REGS();
return XREGS[arity]; return rc;
} }
catch (YAPError e) catch (YAPError e)
{ {

View File

@ -439,8 +439,9 @@ private:
//> call a deterninistic predicate: the user will construct aterm of //> call a deterninistic predicate: the user will construct aterm of
//> arity N-1. YAP adds an extra variable which will have the //> arity N-1. YAP adds an extra variable which will have the
//> output. //> output.
YAPTerm fun(YAPTerm t) { return YAPTerm(fun(t.term())); }; YAPTerm funCall(YAPTerm t) { return YAPTerm(fun(t.term())); };
Term fun(Term t); Term fun(Term t);
Term fun(YAPTerm t) { return fun(t.term()); };
//> set a StringFlag, usually a path //> set a StringFlag, usually a path
//> //>
bool setStringFlag(std::string arg, std::string path) bool setStringFlag(std::string arg, std::string path)

View File

@ -216,7 +216,9 @@ INLINE_ONLY inline EXTERN yhandle_t Yap_InitHandle__(Term t USES_REGS) {
yhandle_t old_slots = LOCAL_CurHandle; yhandle_t old_slots = LOCAL_CurHandle;
ensure_slots(1 PASS_REGS); ensure_slots(1 PASS_REGS);
if (IsVarTerm(t) && (H0 > (CELL*)t || (CELL*)t > HR)) { if (t==0) {
t = MkVarTerm();
} else if (IsVarTerm(t) && (H0 > (CELL*)t || (CELL*)t > HR)) {
RESET_VARIABLE(HR); RESET_VARIABLE(HR);
Yap_unify(t,(CELL)HR); t = (CELL)HR++; Yap_unify(t,(CELL)HR); t = (CELL)HR++;
} }

View File

@ -112,7 +112,10 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o) {
} else } else
#endif #endif
{ {
PyObject *pobj = PyUnicode_DecodeUTF8(s, strlen(s), NULL); // char *p = malloc(strlen(s)+1);
//strcpy(p, s);
PyObject *pobj = PyUnicode_FromString(s);
Py_IncRef(pobj);
return CHECKNULL(t, pobj); return CHECKNULL(t, pobj);
} }
} break; } break;

View File

@ -1,48 +1,98 @@
import yap
import os.path import os.path
import sys import sys
# debugging support. # debugging support.
import pdb # import pdb
from collections import namedtuple from collections import namedtuple
from yap import *
class Engine( ):
def __init__(self, args=None):
def run(self, g, m=None):
if m:
self.mgoal(g, m)
else:
self.goal(g)
def f(self, g):
self.E.fun(g)
class EngineArgs( YAPEngineArgs ):
""" Interface to Engine Options class"""
class Predicate( YAPPredicate ):
""" Interface to Generic Predicate"""
class PrologPredicate( YAPPrologPredicate ):
""" Interface to Prolog Predicate"""
global engine, handler
yap_lib_path = os.path.dirname(__file__) yap_lib_path = os.path.dirname(__file__)
use_module = namedtuple('use_module', 'file') use_module = namedtuple('use_module', 'file')
bindvars = namedtuple('bindvars', 'list') bindvars = namedtuple('bindvars', 'list')
library = namedtuple('library', 'list') library = namedtuple('library', 'list')
v = namedtuple( '_', 'slot') v = namedtuple( 'v', 'slot')
yap_query = namedtuple( 'yap_query', 'query owner')
jupyter_query = namedtuple( 'jupyter_query', 'vars dict')
python_query = namedtuple( 'python_query', 'vars dict')
yapi_query = namedtuple( 'yapi_query', 'vars dict')
show_answer = namedtuple( 'show_answer', 'vars dict')
set_prolog_flag = namedtuple('set_prolog_flag', 'flag new_value')
def v():
return yap.YAPVarTerm()
def numbervars( engine, l ): def numbervars( q ):
rc = engine.fun(bindvars(l)) Dict = {}
if True:
engine.goal(show_answer( q.namedVars(), Dict))
return Dict
rc = q.namedVarsVector()
q.r = q.goal().numbervars()
print( rc )
o = [] o = []
for i in rc: for i in rc:
if i[0] == "=": if len(i) == 2:
o = o + [i[1]] do = str(i[0]) + " = " + str( i[1] ) + "\n"
o += do
print(do)
else: else:
o = o +[i] do = str(i[0]) + " = " + str( i[1] ) + "\n"
o += do
print(do)
return o return o
def query_prolog(engine, s):
def answer(q): def answer(q):
try: try:
return q.next() v = q.next()
if v:
print( bindings )
return v
except Exception as e: except Exception as e:
print(e.args[1]) print(e.args[1])
return False return False
def query_prolog(engine, s):
import pdb; pdb.set_trace()
# #
# construct a query from a one-line string # construct a query from a one-line string
# q is opaque to Python # q is opaque to Python
q = engine.query(s) bindings = {}
q = engine.query(python_query(s, bindings))
# vs is the list of variables # vs is the list of variables
# you can print it out, the left-side is the variable name, # you can print it out, the left-side is the variable name,
# the right side wraps a handle to a variable # the right side wraps a handle to a variable
# pdb.set_trace() # pdb.set_trace()
vs = q.namedVars() # #pdb.set_trace()
#pdb.set_trace()
# atom match either symbols, or if no symbol exists, sttrings, In this case # atom match either symbols, or if no symbol exists, sttrings, In this case
# variable names should match strings # variable names should match strings
#for eq in vs: #for eq in vs:
@ -52,28 +102,11 @@ def query_prolog(engine, s):
ask = True ask = True
# launch the query # launch the query
while answer(q): while answer(q):
# this new vs should contain bindings to vars
vs= q.namedVars()
if vs != []:
gs = numbervars( engine, vs)
i=0
# iterate
for eq in gs:
name = eq[0]
binding = eq[1]
# this is tricky, we're going to bind the variables in the term so thay we can
# output X=Y. The Python way is to use dictionares.
#Instead, we use the T function to tranform the Python term back to Prolog
if name != binding:
print(name + " = " + str(binding))
#ok, that was Prolog code
else:
print("yes")
# deterministic = one solution # deterministic = one solution
if q.deterministic(): if q.deterministic():
# done # done
q.close() q.close()
return return True, True
if ask: if ask:
s = input("more(;), all(*), no(\\n), python(#) ?").lstrip() s = input("more(;), all(*), no(\\n), python(#) ?").lstrip()
if s.startswith(';') or s.startswith('y'): if s.startswith(';') or s.startswith('y'):
@ -92,15 +125,7 @@ def query_prolog(engine, s):
q.close() q.close()
return return
def live(**kwargs):
def live():
yap_lib_path = os.path.dirname(__file__)
args = yap.YAPEngineArgs()
args.setYapShareDir(os.path.join(yap_lib_path,"prolog"))
args.setYapLibDir(yap_lib_path)
#args.setYapPrologBootFile(os.path.join(yap_lib_path."startup.yss"))
engine = yap.YAPEngine(args)
engine.goal( use_module(library('yapi') ) )
loop = True loop = True
while loop: while loop:
try: try:
@ -121,6 +146,18 @@ def live():
print("Unexpected error:", sys.exc_info()[0]) print("Unexpected error:", sys.exc_info()[0])
raise raise
engine.close() engine.close()
def boot_yap(**kwargs):
args = EngineArgs()
yap_lib_path = os.path.dirname(__file__)
args.setYapShareDir(os.path.join(yap_lib_path,"prolog"))
args.setYapLibDir(yap_lib_path)
args.setSavedState(os.path.join(yap_lib_path,"startup.yss"))
engine = YAPEngine(args)
engine.goal( set_prolog_flag('verbose', 'silent' ) )
engine.goal( use_module(library('yapi') ) )
retun engine
# #
# initialize engine # initialize engine
# engine = yap.YAPEngine(); # engine = yap.YAPEngine();
@ -129,4 +166,6 @@ def live():
# #
if __name__ == "__main__": if __name__ == "__main__":
engine = boot_yap()
handler = numbervars
live() live()

View File

@ -1,4 +1,4 @@
%% @file yapi.yap drye%% @file yapi.yap
%% @brief support yap shell %% @brief support yap shell
%% %%
:- module(yapi, [python_query/2, :- module(yapi, [python_query/2,
@ -113,6 +113,3 @@ output([V=B], S) :-
output([V=B|_Ns], S) :- output([V=B|_Ns], S) :-
format( S, '~a = ~q.~n', [V, B]), format( S, '~a = ~q.~n', [V, B]),
fail. fail.