This commit is contained in:
Vitor Santos Costa 2018-02-26 21:38:19 +00:00
parent 530246688c
commit 3a36285bb2
12 changed files with 1767 additions and 1807 deletions

View File

@ -1091,14 +1091,17 @@ bool set_clause_info(yamop *codeptr, PredEntry *pp) {
Term ts[2]; Term ts[2];
void *begin; void *begin;
if (pp->ArityOfPE == 0) { if (pp->ArityOfPE == 0) {
LOCAL_ActiveError->prologPredName = RepAtom((Atom) pp->FunctorOfPred)->StrOfAE; LOCAL_ActiveError->prologPredName =
RepAtom((Atom)pp->FunctorOfPred)->StrOfAE;
LOCAL_ActiveError->prologPredArity = 0; LOCAL_ActiveError->prologPredArity = 0;
} else { } else {
LOCAL_ActiveError->prologPredName = RepAtom(NameOfFunctor(pp->FunctorOfPred))->StrOfAE; LOCAL_ActiveError->prologPredName =
RepAtom(NameOfFunctor(pp->FunctorOfPred))->StrOfAE;
LOCAL_ActiveError->prologPredArity = pp->ArityOfPE; LOCAL_ActiveError->prologPredArity = pp->ArityOfPE;
} }
LOCAL_ActiveError->prologPredModule = LOCAL_ActiveError->prologPredModule =
(pp->ModuleOfPred ? RepAtom(AtomOfTerm(pp->ModuleOfPred))->StrOfAE : "prolog"); (pp->ModuleOfPred ? RepAtom(AtomOfTerm(pp->ModuleOfPred))->StrOfAE
: "prolog");
LOCAL_ActiveError->prologPredFile = RepAtom(pp->src.OwnerFile)->StrOfAE; LOCAL_ActiveError->prologPredFile = RepAtom(pp->src.OwnerFile)->StrOfAE;
if (codeptr->opc == UNDEF_OPCODE) { if (codeptr->opc == UNDEF_OPCODE) {
LOCAL_ActiveError->prologPredFirstLine = 0; LOCAL_ActiveError->prologPredFirstLine = 0;
@ -1389,7 +1392,7 @@ static Term BuildActivePred(PredEntry *ap, CELL *vect) {
arity_t i; arity_t i;
if (!ap->ArityOfPE) { if (!ap->ArityOfPE) {
return MkVarTerm(); return MkAtomTerm((Atom)ap->FunctorOfPred);
} }
for (i = 0; i < ap->ArityOfPE; i++) { for (i = 0; i < ap->ArityOfPE; i++) {
Term t = Deref(vect[i]); Term t = Deref(vect[i]);
@ -1639,8 +1642,7 @@ static Int p_choicepoint_info(USES_REGS1) {
Atom at = AtomLive; Atom at = AtomLive;
t = MkAtomTerm(at); t = MkAtomTerm(at);
pe = RepPredProp(PredPropByAtom(at, CurrentModule)); pe = RepPredProp(PredPropByAtom(at, CurrentModule));
} } break;
break;
case _Ystop: case _Ystop:
default: default:
return FALSE; return FALSE;
@ -2008,6 +2010,8 @@ static Term build_bug_location(yamop *codeptr, PredEntry *pe) {
else else
p[1] = MkAtomTerm((Atom)pe->FunctorOfPred); p[1] = MkAtomTerm((Atom)pe->FunctorOfPred);
p[2] = MkIntegerTerm(pe->ArityOfPE); p[2] = MkIntegerTerm(pe->ArityOfPE);
p[3] = TermNil;
p[4] = MkIntTerm(0);
if (pe->src.OwnerFile) { if (pe->src.OwnerFile) {
p[3] = MkAtomTerm(pe->src.OwnerFile); p[3] = MkAtomTerm(pe->src.OwnerFile);
if (pe->PredFlags & MegaClausePredFlag) { if (pe->PredFlags & MegaClausePredFlag) {
@ -2043,10 +2047,12 @@ static Term build_bug_location(yamop *codeptr, PredEntry *pe) {
p[4] = MkIntTerm(0); p[4] = MkIntTerm(0);
} }
} }
} else if (pe->OpcodeOfPred == UNDEF_OPCODE) { }
else if (pe->OpcodeOfPred == UNDEF_OPCODE) {
RESET_VARIABLE(p + 3); RESET_VARIABLE(p + 3);
RESET_VARIABLE(p + 4); RESET_VARIABLE(p + 4);
} else { }
else {
// by default, user_input // by default, user_input
p[3] = MkAtomTerm(AtomUserIn); p[3] = MkAtomTerm(AtomUserIn);
p[4] = MkIntTerm(0); p[4] = MkIntTerm(0);

View File

@ -233,15 +233,16 @@ static const char * join(const char *s, ...) {
CACHE_REGS CACHE_REGS
va_list args; va_list args;
va_start(args , s); va_start(args , s);
int lvl = push_text_stack(); // int lvl = push_text_stack();
char *buf = Malloc(FILENAME_MAX+1); char *buf = malloc(FILENAME_MAX+1);
if (s && s[0]) if (s && s[0])
strcpy(buf, s); strcpy(buf, s);
while (true) { while (true) {
const char *fmt = va_arg(args, char *); const char *fmt = va_arg(args, char *);
if (fmt == NULL) { if (fmt == NULL) {
va_end(args); va_end(args);
return pop_output_text_stack(lvl,buf); // return pop_output_text_stack(lvl,buf);
return buf;
} }
strcat(buf, fmt); strcat(buf, fmt);
} }

View File

@ -186,7 +186,6 @@ public:
/// @brief Setup all arguments to a new engine /// @brief Setup all arguments to a new engine
struct X_API YAPEngineArgs : YAP_init_args { struct X_API YAPEngineArgs : YAP_init_args {
public: public:
YAPEngineArgs() { YAPEngineArgs() {
// const std::string *s = new std::string("startup.yss"); // const std::string *s = new std::string("startup.yss");
@ -223,30 +222,19 @@ public:
strcpy((char *)LIBDIR, fl); strcpy((char *)LIBDIR, fl);
}; };
inline const char *getLIBDIR() { return LIBDIR; }; inline const char *setINPUT_STARTUP(const char *fl) {
INPUT_STARTUP = (const char *)malloc(strlen(fl) + 1);
inline void setSHAREDIR(const char *fl) {
SHAREDIR = (const char *)malloc(strlen(fl) + 1);
strcpy((char *)SHAREDIR, fl);
};
inline const char *getSHAREDIR() { return SHAREDIR; };
inline void setINPUT_RESTORE(const char *fl) {
STARTUP = (const char *)malloc(strlen(fl) + 1);
strcpy((char *)INPUT_STARTUP, fl); strcpy((char *)INPUT_STARTUP, fl);
}; };
inline const char *getINPUT_STARTUP() { return INPUT_STARTUP; }; inline const char *getINPUT_STARTUP() { return INPUT_STARTUP; };
inline void setOUTPUT_RESTORE(const char *fl) { inline void setOUTPUT_RESTORE(const char *fl) {
STARTUP = (const char *)malloc(strlen(fl) + 1); OUTPUT_STARTUP = (const char *)malloc(strlen(fl) + 1);
strcpy((char *)OUTPUT_STARTUP, fl); strcpy((char *)OUTPUT_STARTUP, fl);
}; };
inline const char *getINPUT_STARTUP() { return OUTPUT_STARTUP; }; inline const char *getOUTPUT_STARTUP() { return OUTPUT_STARTUP; };
inline void setBOOTFILE(const char *fl) { inline void setBOOTFILE(const char *fl) {
BOOTFILE = (const char *)malloc(strlen(fl) + 1); BOOTFILE = (const char *)malloc(strlen(fl) + 1);
@ -287,7 +275,6 @@ public:
inline void setArgv(char **fl) { Argv = fl; }; inline void setArgv(char **fl) { Argv = fl; };
inline char **getArgv() { return Argv; }; inline char **getArgv() { return Argv; };
}; };
/** /**

View File

@ -2041,9 +2041,9 @@ significant byte first (like Motorola and SPARC, unlike Intel). */
#endif #endif
/* init-time boot */ /* init-time boot */
##ifndef YAP_OUTPUT_STARTUP #ifndef YAP_OUTPUT_STARTUP
##define YAP_OUTPUT_STARTUP "${CMAKE_BINARY_DIR}/${YAP_STARTUP}" #define YAP_OUTPUT_STARTUP "${CMAKE_BINARY_DIR}/${YAP_STARTUP}"
##endif #endif
/* HP-UX old socket stuff */ /* HP-UX old socket stuff */
#ifndef _XOPEN_SOURCE #ifndef _XOPEN_SOURCE

View File

@ -2196,7 +2196,7 @@ X_API int PL_initialise(int myargc, char **myargv) {
#if BOOT_FROM_SAVED_STATE #if BOOT_FROM_SAVED_STATE
init_args.STARTUP = "startup.yss"; init_args.STARTUP = "startup.yss";
#else #else
init_args.STARTUP = NULL; init_args.INPUT_STARTUP = NULL;
#endif #endif
init_args.LIBDIR = NULL; init_args.LIBDIR = NULL;
init_args.BOOTFILE = NULL; init_args.BOOTFILE = NULL;

View File

@ -31,14 +31,14 @@ static void *
py_open(VFS_t *me, int sno, const char *name, py_open(VFS_t *me, int sno, const char *name,
const char *io_mode) { const char *io_mode) {
#if HAVE_STRCASESTR #if HAVE_STRCASESTR
if (strcasestr(name, "//python/") == name) if (strcasestr(name, "/python/") == name)
name += strlen("//python/"); name += strlen("/python/");
#else #else
if (strstr(name, "//python/") == name) if (strstr(name, "/python/") == name)
name += strlen("//python/"); name += strlen("/python/");
#endif #endif
StreamDesc *st = YAP_RepStreamFromId(sno); StreamDesc *st = YAP_RepStreamFromId(sno);
fprintf(stderr,"opened %p\n"); fprintf(stderr,"opened %d\n", sno);
// we assume object is already open, so there is no need to open it. // we assume object is already open, so there is no need to open it.
PyObject *stream = string_to_python(name, true, NULL); PyObject *stream = string_to_python(name, true, NULL);
if (stream == Py_None) if (stream == Py_None)
@ -133,8 +133,8 @@ static bool init_python_stream(void) {
pystream.name = "python stream"; pystream.name = "python stream";
pystream.vflags = pystream.vflags =
VFS_CAN_WRITE | VFS_CAN_EXEC | VFS_CAN_SEEK | VFS_HAS_PREFIX; VFS_CAN_WRITE | VFS_CAN_EXEC | VFS_CAN_READ | VFS_HAS_PREFIX;
pystream.prefix = "//python/"; pystream.prefix = "/python/";
pystream.suffix = NULL; pystream.suffix = NULL;
pystream.open = py_open; pystream.open = py_open;
pystream.close = py_close; pystream.close = py_close;

View File

@ -1,7 +1,7 @@
%% @file yapi.yap %% @file yapi.yap
%% @brief support yap shell %% @brief support yap shell
%% %%
:- start_low_level_trace.
:- module(yapi, [ :- module(yapi, [
python_ouput/0, python_ouput/0,
show_answer/2, show_answer/2,
@ -10,7 +10,7 @@
python_query/2, python_query/2,
yapi_query/2 yapi_query/2
]). ]).
:- stop_low_level_trace.
:- yap_flag(verbose, verbose). :- yap_flag(verbose, verbose).

View File

@ -5,7 +5,7 @@ import keyword
# debugging support. # debugging support.
# import pdb # import pdb
from collections import namedtuple from collections import namedtuple
import readline
from .yap import * from .yap import *
@ -44,46 +44,48 @@ class EngineArgs( YAPEngineArgs ):
class Predicate( YAPPredicate ): class Predicate( YAPPredicate ):
""" Interface to Generic Predicate""" """ Interface to Generic Predicate"""
class Predicate: def __init__(self, t, module=None):
"""Goal is a predicate instantiated under a specific environment """ super().__init__(t)
def __init__( self, name, args, module=None, engine = None):
self = namedtuple( name, args )
if module:
self.p = YAPPredicate( name, len(self), module )
else:
self.p = YAPPredicate( name, len(self) )
self.e = engine
def goals( self, engine): class Goal(object):
"""Goal is a predicate instantiated under a specific environment """
def __init__(self, g, engine, module="user",program=None, max_answers=None ):
self.g = g
self.e = engine self.e = engine
def __iter__(self): def __iter__(self):
return PrologTableIter(self.e, self.p) return PrologTableIter( self.e, self.g )
def holds(self):
return self.e.run(self._make_())
class PrologTableIter: class PrologTableIter:
def __init__(self, e, goal): def __init__(self, e, query):
try: try:
self.e = e self.e = e
self.q = e.YAPQuery(goal) self.q = e.query(python_query(self, query))
except: except:
print('Error') print('Error')
def __iter__(self): def __iter__(self):
# Iterators are iterables too. # Iterators are iterables too.
# Adding this functions to make them so. # - # Adding this functions to make them so.
return self return self
def next(self): def __next__(self):
if not self.q:
raise StopIteration()
if self.q.next(): if self.q.next():
return goal rc = self.q.bindings
if self.q.port == "exit":
self.close()
return rc
else: else:
if self.q:
self.close()
raise StopIteration()
def close(self):
self.q.close() self.q.close()
self.q = None self.q = None
raise StopIteration()
f2p = {"fails":{}} f2p = {"fails":{}}
for i in range(16): for i in range(16):
@ -148,24 +150,15 @@ def numbervars( q ):
class YAPShell: class YAPShell:
def answer(self, q):
try:
self.bindings = {}
v = q.next()
if v:
print( self.bindings )
return v
except Exception as e:
print(e.args[1])
return False
def query_prolog(self, engine, s):
# import pdb; pdb.set_trace() def query_prolog(self, engine, query):
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(python_query(self, s)) #q = engine.query(python_query(self, s))
# #
# # 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,
@ -179,15 +172,18 @@ class YAPShell:
# print( "Error: Variable Name matches a Python Symbol") # print( "Error: Variable Name matches a Python Symbol")
# return # return
do_ask = True do_ask = True
self.port = "call" self.e = engine
# launch the query bindings = []
while self.answer(q): if not self.q:
if self.port == "exit": self.it = PrologTableIter( self.e, query )
# done for bind in self.it:
q.close() bindings += [bind]
return True, True
if do_ask: if do_ask:
print(bindings)
bindings = []
s = input("more(;), all(*), no(\\n), python(#) ?").lstrip() s = input("more(;), all(*), no(\\n), python(#) ?").lstrip()
else:
s = ";"
if s.startswith(';') or s.startswith('y'): if s.startswith(';') or s.startswith('y'):
continue continue
elif s.startswith('#'): elif s.startswith('#'):
@ -200,12 +196,17 @@ class YAPShell:
continue continue
else: else:
break break
if self.q:
self.os = query
if bindings:
return True,bindings
print("No (more) answers") print("No (more) answers")
q.close() return False, None
return
def live(self, engine, **kwargs): def live(self, engine, **kwargs):
loop = True loop = True
self.q = None
while loop: while loop:
try: try:
s = input("?- ") s = input("?- ")

View File

@ -20,7 +20,7 @@
%% ). %% ).
:- reexport(library(yapi)). %:- reexport(library(yapi)).
:- use_module(library(lists)). :- use_module(library(lists)).
:- use_module(library(maplist)). :- use_module(library(maplist)).
:- use_module(library(python)). :- use_module(library(python)).
@ -28,6 +28,7 @@
:- python_import(sys). :- python_import(sys).
jupyter_query(Self, Cell, Line ) :- jupyter_query(Self, Cell, Line ) :-
start_low_level_trace,
setup_call_cleanup( setup_call_cleanup(
enter_cell(Self), enter_cell(Self),
jupyter_cell(Self, Cell, Line), jupyter_cell(Self, Cell, Line),
@ -61,15 +62,15 @@ blankc('\n').
blankc('\t'). blankc('\t').
enter_cell(_Self) :- enter_cell(_Self) :-
open('//python/input', read, Input, []), open('/python/input', read, Input, []),
open('//python/sys.stdout', append, Output, []), open('/python/sys.stdout', append, Output, []),
open('//python/sys.stdout', append, Error, []), open('/python/sys.stdout', append, Error, []),
set_prolog_flag(user_input, Input), set_prolog_flag(user_input, Input),
set_prolog_flag(user_output, Output), set_prolog_flag(user_output, Output),
set_prolog_flag(user_error, Error). set_prolog_flag(user_error, Error).
exit_cell(_Self) :- exit_cell(_Self) :-
%close( user_input), close( user_input),
close( user_output), close( user_output),
close( user_error). close( user_error).

View File

@ -106,6 +106,7 @@ class YAPInputSplitter(InputSplitter):
def validQuery(self, text, line=None): def validQuery(self, text, line=None):
"""Return whether a legal query """Return whether a legal query
""" """
print("valid")
if not line: if not line:
(_,line,_) = self.shell.prolog_cell(text) (_,line,_) = self.shell.prolog_cell(text)
line = line.strip().rstrip() line = line.strip().rstrip()
@ -524,67 +525,27 @@ class YAPRun:
self.yapeng.mgoal(errors(self,text),"user") self.yapeng.mgoal(errors(self,text),"user")
return self.errors return self.errors
def jupyter_query(self, s): def jupyter_query(self, s, mx):
# #
# construct a self.query from a one-line string # construct a self.query from a one-line string
# self.q is opaque to Python # self.q is opaque to Python
iterations = 0 iterations = 0
self.shell.bindings = {} bindings = []
if self.q and s != self.os:
self.q.close()
self.q = None
if not self.q:
#import pdb; pdb.set_trace()
self.shell.port = "call"
program,query,_ = self.prolog_cell(s) program,query,_ = self.prolog_cell(s)
self.q = self.yapeng.query(jupyter_query(self, program, query)) if query == self.shell.os:
self.shell.Solutions = [] q = self.shell.q
if not self.q: self.shell.os = None
return True, []
self.os = s
# vs is the list of variables
# you can print it out, the left-side is the variable name,
# the right side wraps a handle to a variable
# pdb.set_trace()
# #pdb.set_trace()
# atom match either symbols, or if no symbol exists, sttrings, In this case
# variable names should match strings
#for eq in vs:
# if not isinstance(eq[0],str):x
# print( "Error: Variable Name matches a Python Symbol")
# return
# ask = True
# launch the query
# run the new command using the given tracer
while True:
iterations = iterations - 1
rc = YAPRun.answer(self, self.q)
if rc:
# deterministic = one solution
#Dict = {}
#engine.goal(show_answer( q.namedVars(), Dict))
self.shell.Solutions += [self.shell.bindings]
if self.shell.port == "exit":
# done
self.q.close()
self.q = None
self.os = ""
return True, self.shell.Solutions
if iterations == 0:
return True, self.shell.Solutions
else: else:
print("No (more) answers") q = Goal(jupyter_query(self, query), self.yapeng, module="user",program=program)
self.q.close() for q in q:
self.q = None bindings += [q.bindings()]
self.os = '' iterations += 1
return True, self.shell.Solutions if mx == iterations:
break
def answer(self, q): if q:
try: self.shell.os = query
return q.next() self.shell.q = q
except Exception as e: return bindings
self.yapeng.goal(exit_cell(self))
return False, None
def _yrun_cell(self, raw_cell, store_history=True, silent=False, def _yrun_cell(self, raw_cell, store_history=True, silent=False,
@ -690,9 +651,9 @@ class YAPRun:
if store_history: if store_history:
self.shell.history_manager.store_inputs(self.shell.execution_count, self.shell.history_manager.store_inputs(self.shell.execution_count,
cell, raw_cell) cell, raw_cell)
silent = False
if not silent: if not silent:
self.shell.logger.log(cell, raw_cell) self.shell.logger.log(cell, raw_cell)
# # Display the exception if input processing failed. # # Display the exception if input processing failed.
# if preprocessing_exc_tuple is not None: # if preprocessing_exc_tuple is not None:
# self.showtraceback(preprocessing_exc_tuple) # self.showtraceback(preprocessing_exc_tuple)

View File

@ -71,10 +71,10 @@ elseif(CMAKE_CROSSCOMPILING)
) )
else () else ()
add_custom_target(STARTUP ALL add_custom_target(STARTUP ALL
DEPENDS ${CMAKE_BUILD_DIR}/${YAP_STARTUPFILE} DEPENDS ${CMAKE_TOP_BINARY_DIR}/${YAP_STARTUP}
) )
add_custom_command(OUTPUT ${CMAKE_TOP_BINARY_DIR}/${YAP_STARTUP} add_custom_command(OUTPUT ${CMAKE_TOP_BINARY_DIR}/${YAP_STARTUP}
COMMAND yap-bin -B${CMAKE_SOURCE_DIR}/pl/boot.yap --output-saved-state=${CMAKE_TOP_BINARY_DIR}/${YAP_STARTUP} COMMAND yap-bin -B
VERBATIM VERBATIM
DEPENDS ${PL_BOOT_SOURCES} yap-bin DEPENDS ${PL_BOOT_SOURCES} yap-bin
) )

View File

@ -365,6 +365,7 @@ system_module(Mod) :-
functor(G0, N, K), functor(G0, N, K),
'$autoloader_find_predicate'(G0,ExportingMod), '$autoloader_find_predicate'(G0,ExportingMod),
ExportingMod \= ImportingMod, ExportingMod \= ImportingMod,
writeln((ExportingMod,ImportingMod,G0,G0, N ,K)),
(recordzifnot('$import','$import'(ExportingMod,ImportingMod,G0,G0, N ,K),_) -> true ; true ). (recordzifnot('$import','$import'(ExportingMod,ImportingMod,G0,G0, N ,K),_) -> true ; true ).
@ -491,9 +492,11 @@ export_list(Module, List) :-
G1=..[N1|Args], G1=..[N1|Args],
( '$check_import'(M0,ContextMod,N1,K) -> ( '$check_import'(M0,ContextMod,N1,K) ->
( ContextMod == prolog -> ( ContextMod == prolog ->
writeln((M0,ContextMod,G0,G1,N1,K)),
recordzifnot('$import','$import'(M0,user,G0,G1,N1,K),_), recordzifnot('$import','$import'(M0,user,G0,G1,N1,K),_),
fail fail
; ;
writeln((M0,ContextMod,G0,G1,N1,K)),
recordaifnot('$import','$import'(M0,ContextMod,G0,G1,N1,K),_), recordaifnot('$import','$import'(M0,ContextMod,G0,G1,N1,K),_),
fail fail
; ;