This commit is contained in:
Vitor Santos Costa 2018-03-12 15:11:59 +00:00
parent 31fd3eb344
commit 1a8c26b886
32 changed files with 442 additions and 307 deletions

View File

@ -2954,7 +2954,7 @@ yamop *Yap_PredIsIndexable(PredEntry *ap, UInt NSlots, yamop *next_pc) {
if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) {
CleanCls(&cint);
Yap_Error(RESOURCE_ERROR_HEAP, TermNil, LOCAL_ErrorMessage);
return FAILCODE;
return NULL;
}
} else if (setjres == 4) {
restore_machine_regs();
@ -2962,7 +2962,7 @@ yamop *Yap_PredIsIndexable(PredEntry *ap, UInt NSlots, yamop *next_pc) {
if (!Yap_growtrail(LOCAL_Error_Size, FALSE)) {
CleanCls(&cint);
Yap_Error(RESOURCE_ERROR_TRAIL, TermNil, LOCAL_ErrorMessage);
return FAILCODE;
return NULL;
}
} else if (setjres != 0) {
restore_machine_regs();
@ -2970,7 +2970,7 @@ yamop *Yap_PredIsIndexable(PredEntry *ap, UInt NSlots, yamop *next_pc) {
if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) {
Yap_Error(RESOURCE_ERROR_HEAP, TermNil, LOCAL_ErrorMessage);
CleanCls(&cint);
return FAILCODE;
return NULL;
}
}
restart_index:
@ -2983,7 +2983,7 @@ restart_index:
if (compile_index(&cint) == (UInt)FAILCODE) {
Yap_ReleaseCMem(&cint);
CleanCls(&cint);
return FAILCODE;
return NULL;
}
#if DEBUG
if (GLOBAL_Option['i' - 'a' + 1]) {

View File

@ -689,10 +689,10 @@ if (PYTHONLIBS_FOUND AND SWIG_FOUND)
find_python_module(wheel)
find_python_module(setuptools)
find_python_module(backcall)
if (PY_JUPYTER AND PY_WHEEL AND PY_SETUPTOOLS AND PY_BACKCALL)
add_subdirectory(packages/python/yap_kernel)
ENDIF ()
endif ()

View File

@ -239,10 +239,10 @@ Term &YAPTerm::operator[](arity_t i) {
tf = TailOfTerm(t0);
RECOVER_MACHINE_REGS();
tf = RepPair(tf)[i];
}
RECOVER_MACHINE_REGS();
Yap_Error(TYPE_ERROR_COMPOUND, tf, "");
throw YAPError();
} else {
Yap_Error(TYPE_ERROR_COMPOUND, t0, "");
}
RECOVER_MACHINE_REGS();
}
Term &YAPListTerm::operator[](arity_t i) {
@ -377,8 +377,7 @@ Term YAPListTerm::car() {
return (HeadOfTerm(to));
else {
Yap_Error(TYPE_ERROR_LIST, to, "");
return 0;
throw YAPError();
return TermUnique;
}
}
@ -432,8 +431,8 @@ bool YAPEngine::call(YAPPredicate ap, YAPTerm ts[]) {
// allow Prolog style exceotion handling
LOCAL_RestartEnv = &buf;
if (sigsetjmp(*LOCAL_RestartEnv, false)) {
return 0;
throw YAPError();
std::cerr << "Restart\n";
//q.e = new YAPError();
}
// don't forget, on success these bindings will still be there);
result = YAP_LeaveGoal(false, &q);
@ -447,8 +446,7 @@ bool YAPEngine::call(YAPPredicate ap, YAPTerm ts[]) {
std::cerr << "Exception received by "
<< YAPApplTerm(ap.functor(), ts).text() << ".\n Forwarded...\n\n";
LOCAL_RestartEnv = oj;
return 0;
throw e;
return false;
}
}
@ -480,8 +478,8 @@ bool YAPEngine::mgoal(Term t, Term tmod) {
// allow Prolog style exception handling
LOCAL_RestartEnv = &buf;
if (sigsetjmp(*LOCAL_RestartEnv, false)) {
return false;
//throw YAPError();
std::cerr << "Restart\n";
//throw new YAPError();
}
// don't forget, on success these guys may create slots
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec ");
@ -557,7 +555,7 @@ Term YAPEngine::fun(Term t) {
sigjmp_buf buf, *oldp = LOCAL_RestartEnv;
LOCAL_RestartEnv = &buf;
if (sigsetjmp(*LOCAL_RestartEnv, false)) {
// throw YAPError();
// throw new YAPError();
LOCAL_RestartEnv = oldp;
RECOVER_MACHINE_REGS();
return 0;
@ -676,14 +674,14 @@ bool YAPQuery::next() {
bool result = false;
sigjmp_buf buf, *oldp = LOCAL_RestartEnv;
Term terr;
e = nullptr;
try {
BACKUP_MACHINE_REGS();
if (!q_open)
return false;
LOCAL_RestartEnv = &buf;
if (sigsetjmp(*LOCAL_RestartEnv, false)) {
// throw YAPError();
return false;
//e = new YAPError();
}
// don't forget, on success these guys may create slots
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec ");
@ -701,11 +699,10 @@ bool YAPQuery::next() {
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "fail");
}
q_state = 1;
if ((terr = Yap_GetException())) {
if ((terr = Yap_GetException())) {
if ((terr = Yap_PeekException())) {
LOCAL_RestartEnv = &buf;
throw YAPError();
}
result = false;
}
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "out %d", result);
@ -846,8 +843,9 @@ void Yap_displayWithJava(int c) {
void YAPEngine::doInit(YAP_file_type_t BootMode, YAPEngineArgs *engineArgs) {
if ((BootMode = YAP_Init(engineArgs)) == YAP_FOUND_BOOT_ERROR) {
return;
throw YAPError();
std::cerr << "Exception received by " << __func__ << "( "
<< "while booting" << ").\n Forwarded...\n\n";
return;
}
/* Begin preprocessor code */
/* live */
@ -903,7 +901,8 @@ PredEntry *YAPPredicate::getPred(YAPTerm &tt, CELL *&outp) {
Yap_ThrowError(INSTANTIATION_ERROR, tt.term(), 0);
else if (IsNumTerm(t))
Yap_ThrowError(TYPE_ERROR_CALLABLE, tt.term(), 0);
throw YAPError();
std::cerr << "Exception received by " << __func__ << "( "
<< YAPTerm(tt).text() << ").\n Forwarded...\n\n";
}
tt.put(t);
if (IsAtomTerm(t)) {
@ -1062,7 +1061,7 @@ Term YAPEngine::top_level(std::string s) {
ARG2 = tp;
ARG3 = MkVarTerm();
if (ARG1 == 0)
YAPError(SYNTAX_ERROR);
Yap_Error(SYNTAX_ERROR, ARG1, "in input query");
YAPPredicate p = YAPPredicate(YAP_TopGoal());
YAPQuery *Q = new YAPQuery(p, 0);
Term ts[2];

View File

@ -34,7 +34,11 @@ class X_API YAPError {
public:
YAPError(){
//ID = LOCAL_ActiveError->errorNo;
if (LOCAL_ActiveError == nullptr)
return;
ID = LOCAL_ActiveError->errorNo;
if (ID != YAP_NO_ERROR) {};
std::cerr << "Error detected" << ID << "\n";
}
/// error handler object with initial data when receiving the error term
YAPError(yap_error_number id, YAPTerm culprit, std::string txt);

View File

@ -46,6 +46,7 @@ class X_API YAPQuery : public YAPPredicate {
YAPTerm goal;
// temporaries
Term tnames, tgoal;
YAPError *e;
inline void setNext() { // oq = LOCAL_execution;
// LOCAL_execution = this;
@ -292,7 +293,8 @@ private:
YAPError yerror;
void doInit(YAP_file_type_t BootMode, YAPEngineArgs *cargs);
YAP_dogoalinfo q;
PredEntry *rewriteUndefEngineQuery(PredEntry *ap, Term &t, Term tmod);
YAPError e;
PredEntry *rewriteUndefEngineQuery(PredEntry *ap, Term &t, Term tmod);
public:
/// construct a new engine; may use a variable number of arguments

View File

@ -1,6 +1,6 @@
// Stuff that must be considered local to a thread or worker
/// Thread Local Variables. This file now follows C syntax.
// Streams
// Macro support
#ifndef LOCAL
#include "Yap.h"
#include "heap.h"
@ -17,6 +17,7 @@
#define LOCAL_INIT_RESTORE(A,B,C,D) A B; C; D;
#endif
/// Current bindings for std streams, includes default s
LOCAL_INIT(int, c_input_stream, 0);
LOCAL_INIT(int, c_output_stream, 1);
LOCAL_INIT(int, c_error_stream, 2);

View File

@ -4,7 +4,7 @@ option(WITH_JAVA "Try to use Java (currently Java 6,7,8)" ON)
if (WITH_JAVA)
#detect java setup, as it is shared between different installations.
find_package(Java 8 COMPONENTS Runtime Development)
find_package(Java 1.8 COMPONENTS Runtime Development)
# find_package(Java COMPONENTS Development)
# find_package(Java COMPONENTS Runtime)
#find_package(JavaLibs)

View File

@ -422,19 +422,19 @@
"%matplotlib inline\n",
"\n",
"main :- \n",
" := import( matplotlib.pyplot ),\n",
" := import( numpy ),\n",
" Plt = matplotlib.pyplot,\n",
" Np = numpy,\n",
" t := Np.arange(0.0, 2.0, 0.01),\n",
" s := 1 + Np.sin(2*Np.pi*t),\n",
" := Plt.plot(t, s),\n",
" := Plt.xlabel(`time (s)`),\n",
" := Plt.ylabel(`voltage (mV)`),\n",
" := Plt.title(`About as simple as it gets, folks`),\n",
" := Plt.grid(true),\n",
" := Plt.savefig(`test2.png`),\n",
" := Plt.show().\n",
" import( matplotlib.pyplot ),\n",
" import( numpy ),\n",
" Plt := matplotlib.pyplot,\n",
" Np := numpy,\n",
" t := np.arange(0.0, 2.0, 0.01),\n",
" s := 1 + np.sin(2*np.pi*t),\n",
" Plt.plot(t, s),\n",
" Plt.xlabel(`time (s)`),\n",
" Plt.ylabel(`voltage (mV)`),\n",
" Plt.title(`About as simple as it gets, folks`),\n",
" Plt.grid(true),\n",
" Plt.savefig(`test2.png`),\n",
" Plt.show().\n",
"\n",
"main"
]

View File

@ -1848,7 +1848,6 @@ static Int close2(USES_REGS1) { /* '$close'(+GLOBAL_Stream) */
Yap_Error(LOCAL_Error_TYPE, tlist, NULL);
}
return false;
return FALSE;
}
// if (args[CLOSE_FORCE].used) {
// }

View File

@ -268,7 +268,8 @@ static Term scanToList(TokEntry *tok, TokEntry *errtok) {
}
tok = tok->TokNext;
}
Yap_DebugPlWriteln(ts[0]);
if (ts[0])
Yap_DebugPlWriteln(ts[0]);
return ts[0];
}
@ -307,7 +308,7 @@ static Int scan_to_list(USES_REGS1) {
}
/**
* Syntax Error Handler
* Syntaax Error Handler
*
* @par tokptr: the sequence of tokens
* @par sno: the stream numbet

View File

@ -1005,11 +1005,7 @@ static void CloseStream(int sno) {
} else if (GLOBAL_Stream[sno].status & (InMemory_Stream_f)) {
Yap_CloseMemoryStream(sno);
}
GLOBAL_Stream[sno].status = Free_Stream_f;
GLOBAL_Stream[sno].vfs = NULL;
GLOBAL_Stream[sno].file = NULL;
Yap_DeleteAliases(sno);
if (LOCAL_c_input_stream == sno) {
if (LOCAL_c_input_stream == sno) {
LOCAL_c_input_stream = StdInStream;
}
if (LOCAL_c_output_stream == sno) {
@ -1018,6 +1014,11 @@ static void CloseStream(int sno) {
if (LOCAL_c_error_stream == sno) {
LOCAL_c_error_stream = StdErrStream;
}
Yap_DeleteAliases(sno);
GLOBAL_Stream[sno].vfs = NULL;
GLOBAL_Stream[sno].file = NULL;
GLOBAL_Stream[sno].status = Free_Stream_f;
/* if (st->status == Socket_Stream_f|Input_Stream_f|Output_Stream_f) {
Yap_CloseSocket();
}

View File

@ -728,7 +728,7 @@ def gecode_version():
os.remove(file_hh)
os.remove(file_txt)
else:
version = "5.0.0"
version = "6.0.0"
GECODE_VERSION = version
return version

View File

@ -664,8 +664,8 @@ static void Yap_InitBackMYDDAS_SQLITE3Preds(void) {
}
X_API void init_sqlite3(void) {
// Yap_InitMYDDAS_SQLITE3Preds();
// Yap_InitBackMYDDAS_SQLITE3Preds();
Yap_InitMYDDAS_SQLITE3Preds();
Yap_InitBackMYDDAS_SQLITE3Preds();
}
#if _ANDROID_

View File

@ -35,6 +35,7 @@ static PyObject *s_to_python(const char *s, bool eval, PyObject *p0) {
// char *ns = Py_Malloc(strlen(s)+1);
/// strcpy(ns,s);
PyObject *pobj = PyUnicode_FromString(s);
Py_INCREF(pobj);
return pobj;
}
}
@ -48,6 +49,8 @@ static PyObject *s_to_python(const char *s, bool eval, PyObject *p0) {
* @return a Python object descriptor or NULL if failed
*/
X_API PyObject *string_to_python(const char *s, bool eval, PyObject *p0) {
char *buf = malloc(strlen(s) + 1), *child;
while ((child = strchr(s, '.')) != NULL) {
size_t len = child - s;
@ -341,6 +344,7 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
AOK(PL_get_arg(1, t, t), NULL);
if (!(dict = PyDict_New()))
return NULL;
Py_INCREF(dict);
DebugPrintf("Dict %p\n", dict);
while (PL_is_functor(t, FUNCTOR_comma2)) {

View File

@ -46,6 +46,7 @@ foreign_t assign_to_symbol(term_t t, PyObject *e) {
PyObject *dic;
if (!lookupPySymbol(s, NULL, &dic))
dic = py_Main;
Py_INCREF(e);
return PyObject_SetAttrString(dic, s, e) == 0;
}
@ -315,12 +316,13 @@ bool python_assign(term_t t, PyObject *exp, PyObject *context) {
if (PySequence_Check(o) && PyInt_Check(i)) {
long int j;
j = PyInt_AsLong(i);
return PySequence_SetItem(o, i, exp) == 0;
return PySequence_SetItem(o, i, exp) == 0;
}
#endif
if (PyDict_Check(o)) {
if (PyDict_SetItem(o, i, exp) == 0)
if (PyDict_SetItem(o, i, exp) == 0) {
return true;
}
}
if (PyObject_SetAttr(o, i, exp) == 0) {
return true;

View File

@ -35,7 +35,7 @@
PyObject *find_obj(PyObject *ob, term_t lhs, bool eval);
#if DEBUG_MEMORY
#if DEBUG_MEMORY||1
#define DebugPrintf(s, op) fprintf(stderr, "%s:%d: " s, __FILE__, __LINE__, op)
#else
#define DebugPrintf(s, op)
@ -85,7 +85,7 @@ extern PyObject *py_ModDict;
extern X_API bool python_in_python;
extern bool python_release_GIL(term_t state);
extern bool python_release_GIL(term_t gstate);
extern term_t python_acquire_GIL(void);
static inline Py_ssize_t get_p_int(PyObject *o, Py_ssize_t def) {
@ -182,7 +182,7 @@ extern void pyErrorHandler__(int line, const char *file, const char *code);
extern PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt);
extern PyObject *compound_to_pytree(term_t t, PyObject *context, bool cvt);
extern PyObject *term_to_python(term_t t, bool eval, PyObject *contextxs,
extern PyObject *term_to_python(term_t t, bool eval, PyObject *context,
bool eval_atom);
extern PyObject *term_to_nametuple(const char *s, arity_t arity, PyObject *);

View File

@ -1014,7 +1014,6 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) {
} else {
char *s = PL_atom_chars(name);
PyObject *ys = lookupPySymbol(s, o, NULL), *pArgs;
DebugPrintf("Tuple %p\n", pArgs);
int i;
term_t tleft = PL_new_term_ref();
bool indict = true;
@ -1037,6 +1036,7 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) {
pArgs = PyTuple_New(i);
}
}
DebugPrintf("Tuple %p\n", pyDict);
if (!indict) {
if (PL_is_variable(tleft)) {
pArg = Py_None;

View File

@ -5,10 +5,45 @@
#include "YapStreams.h"
VFS_t pystream;
YAP_Term TermErrStream, TermOutStream;
static void *py_open(VFS_t *me, int sno, const char *name,
const char *io_mode) {
static int py_put(int sno, int ch)
{
// PyObject *pyw; // buffer
// int pyw_kind;
// PyObject *pyw_data;
StreamDesc *st = YAP_GetStreamFromId(sno);
if (st->user_name == TermOutStream) {
PyGILState_STATE tg = python_acquire_GIL();
PySys_WriteStdout("%C", ch);
python_release_GIL(tg);
return ch;
}
if (st->user_name == TermErrStream) {
PyGILState_STATE tg = python_acquire_GIL();
PySys_WriteStderr("%C", ch);
python_release_GIL(tg);
return ch;
}
char s[2];
PyObject *err;
s[0] = ch;
s[1] = '\0';
PyGILState_STATE g0 = python_acquire_GIL();
PyObject_CallMethodObjArgs(st->u.private_data, PyUnicode_FromString("write"),
PyUnicode_FromString(s), NULL);
python_release_GIL(g0);
if ((err = PyErr_Occurred()))
{
PyErr_SetString(
err,
"Error in put\n"); // %s:%s:%d!\n", __FILE__, __FUNCTION__, __LINE__);
}
return ch;
}
VFS_t pystream;
static void *py_open(VFS_t *me, int sno, const char *name, const char *io_mode) {
#if HAVE_STRCASESTR
if (strcasestr(name, "/python/") == name)
name += strlen("/python/");
@ -17,68 +52,111 @@ static void *py_open(VFS_t *me, int sno, const char *name,
name += strlen("/python/");
#endif
StreamDesc *st = YAP_RepStreamFromId(sno);
// we assume object is already open, so there is no need to open it.
PyObject *stream = string_to_python(name, true, NULL);
if (stream == Py_None)
return NULL;
Py_INCREF(stream);
st->u.private_data = stream;
st->vfs = me;
st->name = YAP_LookupAtom(name);
st->user_name = YAP_MkAtomTerm(st->name);
return stream;
if (strcmp(name,"sys.output") == 0) {
st->user_name = TermOutStream;
} else if(strcmp(name,"sys.error") == 0) {
st->user_name = TermErrStream;
} else {
// we assume object is already open, so there is no need to open it.
PyObject *pystream = string_to_python(name, true, NULL);
if (pystream == Py_None) {
return NULL;
} else {
st->u.private_data = pystream;
st->vfs = me;
st->name = YAP_LookupAtom(name);
st->user_name = YAP_MkAtomTerm(st->name);
}
}
return st;
}
static bool py_close(int sno) { return true; }
static bool py_close(int sno) {
StreamDesc *st = YAP_RepStreamFromId(sno);
Py_DECREF(st->u.private_data);
return true;
}
static int py_put(int sno, int ch) {
// PyObject *pyw; // buffer
// int pyw_kind;
// PyObject *pyw_data;
// PySys_WriteStdout("%C", ch);
// return ch;
char s[2];
StreamDesc *st = YAP_GetStreamFromId(sno);
// PyUnicode_WRITE(pyw_kind, pyw_data, 0, ch);
PyObject *err, *fput = PyObject_GetAttrString(st->u.private_data, "write");
s[0] = ch;
s[1] = '\0';
PyObject_CallMethodObjArgs(st->u.private_data, PyUnicode_FromString("write"),
PyUnicode_FromString(s), NULL);
if ((err = PyErr_Occurred())) {
PyErr_SetString(
err,
"Error in put\n"); // %s:%s:%d!\n", __FILE__, __FUNCTION__, __LINE__);
static bool getLine(int inp) {
char *myrl_line = NULL;
StreamDesc *rl_instream = YAP_RepStreamFromId(inp);
PyObject*prompt = PyUnicode_FromString( "?- "),
*msg = PyUnicode_FromString("");
/* window of vulnerability opened */
myrl_line = PyUnicode_AsUTF8(PyObject_CallFunctionObjArgs(rl_instream->u.private_data,msg,prompt,NULL));
rl_instream->u.irl.ptr = rl_instream->u.irl.buf = (const unsigned char*)myrl_line;
myrl_line = NULL;
return true;
}
static int py_getc(int sno) {
StreamDesc *s = YAP_RepStreamFromId(sno);
int ch;
bool fetch = (s->u.irl.buf == NULL);
if (!fetch || getLine(sno)) {
const unsigned char *ttyptr = s->u.irl.ptr++, *myrl_line = s->u.irl.buf;
ch = *ttyptr;
if (ch == '\0') {
ch = '\n';
free((void *)myrl_line);
s->u.irl.ptr = s->u.irl.buf = NULL;
}
} else {
return EOF;
}
return ch;
}
/**
@brief Yap_ReadlinePeekChar peeks the next char from the
readline buffer, but does not actually grab it.
The idea is to take advantage of the buffering. Special care must be taken
with EOF, though.
*/
static int py_peek(int sno) {
StreamDesc *s = YAP_RepStreamFromId(sno);
int ch;
if (s->u.irl.buf) {
const unsigned char *ttyptr = s->u.irl.ptr;
ch = *ttyptr;
if (ch == '\0') {
ch = '\n';
}
return ch;
}
if (getLine(sno)) {
ch = s->u.irl.ptr[0];
if (ch == '\0') {
ch = '\n';
}
} else {
return EOF;
}
return ch;
}
static int py_get(int sno) {
StreamDesc *s = YAP_GetStreamFromId(sno);
PyObject *fget = PyObject_GetAttrString(s->u.private_data, "read");
PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL);
return PyUnicode_READ_CHAR(pyr, 0);
}
static int py_peek(int sno) {
StreamDesc *s = YAP_GetStreamFromId(sno);
PyObject *fget = PyObject_GetAttrString(s->u.private_data, "peek");
PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL);
return PyUnicode_READ_CHAR(pyr, 0);
}
static int64_t py_seek(int sno, int64_t where, int how) {
StreamDesc *s = YAP_GetStreamFromId(sno);
PyObject *fseek = PyObject_GetAttrString(s->u.private_data, "seek");
StreamDesc *g0 = YAP_RepStreamFromId(sno);
PyGILState_STATE s0 = python_acquire_GIL();
PyObject *fseek = PyObject_GetAttrString(g0->u.private_data, "seek");
PyObject *pyr = PyObject_CallFunctionObjArgs(fseek, PyLong_FromLong(where),
PyLong_FromLong(how), NULL);
return PyLong_AsLong(pyr);
python_release_GIL(s0);
return PyLong_AsLong(pyr);
}
static void py_flush(int sno) {
StreamDesc *s = YAP_GetStreamFromId(sno);
YAP_Term tg = python_acquire_GIL();
PyObject *flush = PyObject_GetAttrString(s->u.private_data, "flush");
PyObject_CallFunction(flush, NULL);
python_release_GIL(tg);
}
#if 0
@ -110,13 +188,15 @@ bool init_python_vfs(void) {
pystream.suffix = NULL;
pystream.open = py_open;
pystream.close = py_close;
pystream.get_char = py_get;
pystream.get_char = py_getc;
pystream.peek_char = py_peek;
pystream.put_char = py_put;
pystream.flush = py_flush;
pystream.seek = py_seek;
pystream.next = GLOBAL_VFS;
GLOBAL_VFS = &pystream;
TermOutStream = YAP_MkAtomTerm(YAP_LookupAtom("std.output"));
TermErrStream = YAP_MkAtomTerm(YAP_LookupAtom("std.error"));
// NULL;
return true;
}

View File

@ -631,9 +631,9 @@ static YAP_Int p_python_threaded(void) {
pyErrorAndReturn(true, false);
}
static PyGILState_STATE gstate;
term_t python_acquire_GIL(void) {
static PyGILState_STATE gstate;
term_t curSlot = PL_new_term_ref();
if (!_threaded)
pyErrorAndReturn(curSlot, false);
@ -643,15 +643,18 @@ term_t python_acquire_GIL(void) {
// if (_locked > 0) { _locked++ ; }
// else
gstate = PyGILState_Ensure();
PL_put_integer(curSlot, gstate);
pyErrorAndReturn(curSlot, false);
}
bool python_release_GIL(term_t curBlock) {
PyGILState_STATE gstate;
PyErr_Clear();
PL_reset_term_refs(curBlock);
if (_threaded) {
PL_get_integer(curBlock, &gstate);
PyGILState_Release(gstate);
}
PL_reset_term_refs(curBlock);
pyErrorAndReturn(true, false);
}

View File

@ -134,7 +134,7 @@ user(P1,P2) :- !,
:= P1,
:= P2.
user:(:= ) :- catch( python:python_proc(F), _, fail ).
user:(:= F) :- catch( python:python_proc(F), _, fail ).
user:( V := F ) :-
python:python_assign(F, V).

View File

@ -11,13 +11,13 @@ set (PYTHON_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/yap4py/yapi.py ${CMAKE_CURRENT_S
SET_SOURCE_FILES_PROPERTIES(../../swig/yap.i PROPERTIES CPLUSPLUS ON)
SET_SOURCE_FILES_PROPERTIES(../../swig/yap.i PROPERTIES SWIG_FLAGS "-O;-py3")
SET_SOURCE_FILES_PROPERTIES(../../swiyap.i PROPERTIES SWIG_MODULE_NAME yap4py.yap)
SET_SOURCE_FILES_PROPERTIES(../../swig/yap.i PROPERTIES SWIG_MODULE_NAME yap4py.yap)
#SET_SOURCE_FILES_PROPERTIES(../../swi/yap.i PROPERTIES OUTPUT_NAME yap)
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap4py)
set(YAP4PY_PL prolog/yapi.yap)
set(YAP4PY_PY yap4py/__init__.py yap4py/__main__.py yap4py/yapi.py)
set(YAP4PY_PY yap4py/__main__.py yap4py/yapi.py)
configure_file("setup.py.in" setup.py)
configure_file("MANIFEST.in" ${CMAKE_CURRENT_BINARY_DIR}/MANIFEST.in)
@ -51,7 +51,7 @@ else()
endif()
add_custom_target( YAP4PY ALL
COMMAND ${SWIG_EXECUTABLE} -c++ -python -O -py3 -module "yap" -addextern -I${CMAKE_SOURCE_DIR}/H -I${CMAKE_SOURCE_DIR}/H/generated -I${CMAKE_SOURCE_DIR}/include
COMMAND ${SWIG_EXECUTABLE} -c++ -python -O -py3 -module "yap" -addextern -I${CMAKE_SOURCE_DIR}/H -I${CMAKE_SOURCE_DIR}/H/generated -I${CMAKE_SOURCE_DIR}/include
-I${CMAKE_SOURCE_DIR}/OPTYap -I${CMAKE_SOURCE_DIR}/os -I${CMAKE_SOURCE_DIR}/utf8proc -I.././.. -I${CMAKE_SOURCE_DIR}/CXX -I${CMAKE_SOURCE_DIR}/packages/python
-outdir ${CMAKE_CURRENT_BINARY_DIR}/yap4py -I${GMP_INCLUDE_DIRS} -DX_API="" -o ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.cxx -oh ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.hh ${SWIG_SOURCES}
COMMAND ${PYTHON_EXECUTABLE} setup.py sdist ${bdist}

View File

@ -10,9 +10,8 @@
python_query/2,
yapi_query/2
]).
:- stop_low_level_trace.
:- yap_flag(verbose, verbose).
:- yap_flag(verbose, silent).
:- use_module( library(lists) ).
@ -22,6 +21,7 @@
:- reexport( library(python) ).
:- python_import(yap4py.yapi).
:- python_import(gc).
%:- start_low_level_trace.
@ -38,6 +38,7 @@
%:- initialization set_preds.
set_preds :-
fail,
current_predicate(P, Q),
functor(Q,P,A),
atom_string(P,S),
@ -47,6 +48,7 @@ set_preds :-
fail),
fail.
set_preds :-
fail,
system_predicate(P/A),
atom_string(P,S),
catch(
@ -61,14 +63,15 @@ argi(N,I,I1) :-
I1 is I+1.
python_query( Caller, String ) :-
Self := Caller.it,
atomic_to_term( String, Goal, VarNames ),
query_to_answer( Goal, VarNames, Status, Bindings),
Self.port := Status,
Caller.port := Status,
% := print( gc.get_referrers(Caller.port)),
write_query_answer( Bindings ),
nl(user_error),
Self.bindings := {},
maplist(in_dict(Self.bindings), Bindings).
Caller.answer := {},
maplist(in_dict(Caller.answer), Bindings).
% := print( "b", gc.get_referrers(Caller.answer)).
in_dict(Dict, var([V0,V|Vs])) :- !,
Dict[V] := V0,

View File

@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) IPython Development Team.
@ -51,24 +51,25 @@ from distutils.core import setup
here = abspath(dirname(__file__))
libpydir = abspath(sysconfig.get_path('platlib'))
libpyauxdir = abspath(os.path.dirname('stdlib'))
#libpyauxdir = abspath(os.path.dirname('stdlib'))
#pkg_root = join(here, name)
here = path.abspath(path.dirname(__file__))
sys.path.insert(0, "${CMAKE_CURRENT_SOURCE_DIR}")
python_libdir = path.abspath(path.dirname("${PYTHON_LIBRARIES}"))
if platform.system() == 'Windows':
local_libs = []
win_libs = ['wsock32','ws2_32']
my_extra_link_args = ['-Wl,-export-all-symbols']
elif platform.system() == 'Darwin':
my_extra_link_args = ['-L','..','-Wl,-rpath','-Wl,${CMAKE_INSTALL_FULL_LIBDIR}']
my_extra_link_args = ['-L','..','-Wl,-rpath,'+abspath(join(sysconfig.get_path('platlib'),'yap4py')),'-Wl,-rpath,${CMAKE_INSTALL_FULL_LIBDIR}','-Wl,-rpath,../yap4py']
win_libs = []
local_libs = ['Py4YAP']
elif platform.system() == 'Linux':
my_extra_link_args = ['-L','..','-Wl,-rpath','-Wl,${CMAKE_INSTALL_FULL_LIBDIR}']
my_extra_link_args = ['-L','..','-Wl,-rpath,'+abspath(join(sysconfig.get_path('platlib'),'yap4py')),'-Wl,-rpath,${CMAKE_INSTALL_FULL_LIBDIR}','-Wl,-rpath,../yap4py']
win_libs = []
local_libs = ['Py4YAP']
@ -78,22 +79,21 @@ elif platform.system() == 'Linux':
native_sources = ["yap4py/yap_wrap.cxx","yap4py/yapi.cpp"]
#gmp_dir = path.abspath(path.dirname("${GMP_LIBRARIES}"))
#python_libdir = path.abspath(path.dirname("${PYTHON_LIBRARIES}")
# Get the long description from the README file
extensions = [Extension('yap4py._yap', native_sources,
extensions = [Extension('_yap', native_sources,
define_macros=[('MAJOR_VERSION', '1'),
('MINOR_VERSION', '0'),
('_YAP_NOT_INSTALLED_', '1'),
('YAP_PYTHON', '1'),
('_GNU_SOURCE', '1')],
runtime_library_dirs=[abspath(sysconfig.get_path('platlib')),
abspath(sysconfig.get_path('platlib'))],
runtime_library_dirs=[
abspath(join(sysconfig.get_path('platlib'),'yap4py')), abspath(sysconfig.get_path('platlib')),'${CMAKE_INSTALL_FULL_LIBDIR}'],
swig_opts=['-modern', '-c++', '-py3',
'-DX_API', '-Iyap4py/include' ],
library_dirs=[".",'../../..'],
library_dirs=[".",'../../..','${CMAKE_INSTALL_FULL_LIBDIR}'],
extra_link_args=my_extra_link_args,
libraries=['Yap','gmp']+win_libs+local_libs,
include_dirs=['${CMAKE_SOURCE_DIR}/H',
@ -122,7 +122,7 @@ setup_args = dict(
scripts=glob(join('scripts', '*')),
packages=['yap4py'],
ext_modules=extensions,
py_modules=[],
sources=['yap4py/yapi.py','yap4py/yap.py','yap4py/__main__.py','yap4py/__init_.py'],
# package_data=package_data,
include_package_data=True,
data_files = data_files,

View File

@ -16,15 +16,18 @@ if platform.system() == 'Windows':
ctypes.WinDLL(dll)
elif platform.system() == 'Darwin':
def load( dll ):
dll = glob.glob(os.path.join(os.path.realpath(__file__),dll))[0]
dll = glob.glob(os.path.join(os.path.dirname(__file__),dll))[0]
dll = os.path.abspath(dll)
ctypes.CDLL(dll)
# load('libYap.dylib')
# load('libPy4YAP.dylib')
#load( '_yap*.dylib' )
print('loaded ',dll)
# try:
# load( '_yap*.so' )
# except:
# load( '_yap*.dylib' )
else:
def load( dll ):
dll = glob.glob(os.path.join(os.path.realpath(__file__),dll))[0]
dll = glob.glob(os.path.join(os.path.dirname(__file__),dll))[0]
dll = os.path.abspath(dll)
ctypes.CDLL(dll)
# \`load('_yap*.so')
load('_yap*.so')

View File

@ -47,24 +47,21 @@ class Predicate( YAPPredicate ):
def __init__(self, t, module=None):
super().__init__(t)
class Goal(object):
class IQuery(YAPQuery):
"""Goal is a predicate instantiated under a specific environment """
def __init__(self, engine, g):
self.q = engine.query(g)
self.e = engine
self = engine.query(g)
self.port = "call"
self.bindings = None
def __iter__(self):
return PrologTableIter( self.e, self )
return PrologTableIter( self )
class PrologTableIter:
def __init__(self, e, g):
def __init__(self, q):
try:
self.e = e
self.g = g
self.q = g.q
self.q = q
except:
print('Error')
@ -77,9 +74,9 @@ class PrologTableIter:
if not self.q:
raise StopIteration()
if self.q.next():
rc = self.g.bindings
if self.g.port == "exit":
self.close()
rc = self.q.bindings
if self.q.port == "exit":
self.q.close()
return rc
else:
if self.q:
@ -179,7 +176,7 @@ class YAPShell:
bindings = []
g = python_query(self, query)
if not self.q:
self.it = Goal( engine, g )
self.it = IQuery( engine, g )
for bind in self.it:
bindings += [bind]
if do_ask:

View File

@ -64,6 +64,8 @@ yap_ipython/frontend.py
yap_ipython/parallel.py
yap_ipython/html.py
yap_ipython/__main__.py
_version.py
yap_ipython/_version.py
yap_ipython/testing/iptest.py
yap_ipython/testing/skipdoctest.py
yap_ipython/testing/tools.py
@ -387,7 +389,7 @@ set(FILES ${PYTHON_SOURCES} ${PL_SOURCES} ${EXTRAS} ${RESOURCES})
set(SETUP_PY ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap.tgz
COMMAND ${CMAKE_COMMAND} -E tar cf ${CMAKE_CURRENT_BINARY_DIR}/yap.tgz ${FILES}
COMMAND ${CMAKE_COMMAND} -E tar cf ${CMAKE_CURRENT_BINARY_DIR}/yap.tgz ${FILES}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
@ -421,13 +423,14 @@ add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-
add_custom_target(YAP_KERNEL ALL
COMMAND ${CMAKE_COMMAND} -E tar xzf yap.tgz
COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} build sdist bdist
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-64x64.png yap.tgz ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/kernel.js ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/prolog.js
)
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --ignore-installed --no-deps .
install(CODE "execute_process(
COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} build sdist bdist
COMMAND ${PYTHON_EXECUTABLE} -m pip install --ignore-installed --no-deps .
COMMAND ${PYTHON_EXECUTABLE} -m yap_kernel.kernelspec
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})")

View File

@ -40,14 +40,15 @@ here = os.path.abspath(os.path.dirname(__file__))
packages = ['yap_kernel','yap_ipython']
# pkg_root = pjoin(here, name)
# for d, _, _ in os.walk(pjoin(here, 'yap_kernel')):
# if os.path.exists(pjoin(d, '__init__.py')):
# packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
# for d, _, _ in os.walk(pjoin(here, 'yap_ipython')):
# if os.path.exists(pjoin(d, '__init__.py')):
# packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
for d, _, _ in os.walk(pjoin(here, 'yap_kernel')):
if os.path.exists(pjoin(d, '__init__.py')):
packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
for d, _, _ in os.walk(pjoin(here, 'yap_ipython')):
if os.path.exists(pjoin(d, '__init__.py')):
packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
sys.path.insert(0, here)
sys.path.insert(0, pjoin(here,'..','swig'))
package_data = {
'yap_ipython': ['prolog/*.*'],
'yap_kernel': ['resources/*.*']

View File

@ -32,15 +32,15 @@ This is an handy alias to `ipython history trim --keep=0`
class HistoryTrim(BaseYAPApplication):
description = trim_hist_help
backup = Bool(False,
help="Keep the old history file as history.sqlite.<N>"
).tag(config=True)
keep = Int(1000,
help="Number of recent lines to keep in the database."
).tag(config=True)
flags = Dict(dict(
backup = ({'HistoryTrim' : {'backup' : True}},
backup.help
@ -50,7 +50,7 @@ class HistoryTrim(BaseYAPApplication):
aliases=Dict(dict(
keep = 'HistoryTrim.keep'
))
def start(self):
profile_dir = self.profile_dir.location
hist_file = os.path.join(profile_dir, 'history.sqlite')
@ -63,9 +63,9 @@ class HistoryTrim(BaseYAPApplication):
print("There are already at most %d entries in the history database." % self.keep)
print("Not doing anything. Use --keep= argument to keep fewer entries")
return
print("Trimming history to the most recent %d entries." % self.keep)
inputs.pop() # Remove the extra element we got to check the length.
inputs.reverse()
if inputs:
@ -75,7 +75,7 @@ class HistoryTrim(BaseYAPApplication):
sessions = list(con.execute('SELECT session, start, end, num_cmds, remark FROM '
'sessions WHERE session >= ?', (first_session,)))
con.close()
# Create the new history database.
new_hist_file = os.path.join(profile_dir, 'history.sqlite.new')
i = 0
@ -114,18 +114,18 @@ class HistoryTrim(BaseYAPApplication):
print("Backed up longer history file to", backup_hist_file)
else:
os.remove(hist_file)
os.rename(new_hist_file, hist_file)
class HistoryClear(HistoryTrim):
description = clear_hist_help
keep = Int(0,
help="Number of recent lines to keep in the database.")
force = Bool(False,
help="Don't prompt user for confirmation"
).tag(config=True)
flags = Dict(dict(
force = ({'HistoryClear' : {'force' : True}},
force.help),

View File

@ -219,9 +219,9 @@ class ExecutionResult(object):
def raise_error(self):
"""Reraises error if `success` is `False`, otherwise does nothing"""
if self.error_before_exec is not None:
if self.error_before_exec:
raise self.error_before_exec
if self.error_in_exec is not None:
if self.error_in_exec:
raise self.error_in_exec
def __repr__(self):
@ -2598,7 +2598,7 @@ class InteractiveShell(SingletonConfigurable):
with prepended_to_syspath(dname):
try:
for cell in get_cells():
result = self.run_cell(cell, silent=False , shell_futures=shell_futures)
result = self.run_cell(cell, silent=False, shell_futures=shell_futures)
if raise_exceptions:
result.raise_error()
elif not result.success:
@ -2661,6 +2661,9 @@ class InteractiveShell(SingletonConfigurable):
-------
result : :class:`ExecutionResult`
"""
print("go")
result = None
try:
result = self._yrun_cell(
raw_cell, store_history, silent, shell_futures)
@ -2668,6 +2671,7 @@ class InteractiveShell(SingletonConfigurable):
self.events.trigger('post_execute')
if not silent:
self.events.trigger('post_run_cell', result)
print("go", result)
return result
def _run_cell(self, raw_cell, store_history, silent, shell_futures):

View File

@ -11,15 +11,15 @@
* -
*/
%% :- module( jupyter,
%% [jupyter_query/3,
%% errors/2,
%% ready/2,
%% completion/2,
%% ]
%% ).
% :- module( jupyter,
% [jupyter_query/3,
% errors/2,
% ready/2,
% completion/2,
% ]
%% ).
:- [library(hacks)].
:- reexport(library(yapi)).
:- use_module(library(lists)).
@ -32,26 +32,24 @@ jupyter_query(Caller, Cell, Line ) :-
jupyter_cell(Caller, Cell, Line).
jupyter_cell(_Caller, Cell, _) :-
jupyter_consult(Cell),
jupyter_consult(Cell), %stack_dump,
fail.
jupyter_cell( _Caller, _, Line ) :-
blank( Line ),
!.
jupyter_cell( _Caller, _, [] ) :- !.
jupyter_cell( Caller, _, Line ) :-
gated_call(
enter_cell(call),
python_query( Caller, Line ),
Port,
enter_cell(Port)
).
Self := Caller.query,
python_query( Self, Line ).
jupyter_consult(Text) :-
blank( Text ),
!.
jupyter_consult(Cell) :-
open_mem_read_stream( Cell, Stream),
load_files(user:'jupyter cell',[stream(Stream)]).
% Name = 'Inp',
% stream_property(Stream, file_name(Name) ),
load_files(user:'jupyter cell',[stream(Stream)]), !.
%should load_files close?
blank(Text) :-
@ -62,31 +60,18 @@ blankc(' ').
blankc('\n').
blankc('\t').
enter_cell(retry) :-
enter_cell(call).
enter_cell(call) :-
into_cell.
enter_cell(fail) :-
enter_cell(exit).
enter_cell(answer) :-
enter_cell(exit).
enter_cell(exception(_)) :-
enter_cell(exit).
enter_cell(external_exception(_)).
enter_cell(!).
enter_cell(exit) :-
nb_setval(jupyter_cell, off),
close( user_output).
into_cell :-
nb_setval(jupyter_cell, on),
open('/python/sys.input', read, _Input, [bom(false)]),
open('/python/sys.stdout', append, _Output, []),
open('/python/sys.stderr', append, _Error, []),
set_prolog_flag(user_input,_Output),
streams(false) :-
% close( user_input),
close( user_error ),
close( user_output ).
streams(true) :-
% open('/python/input', read, _Input, [alias(user_input),bom(false)]),
open('/python/sys.stdout', append, _Output, [alias(user_output)]),
open('/python/sys.stderr', append, _Error, [alias(user_error)]),
% set_prolog_flag(user_input,_Input),
set_prolog_flag(user_output,_Output),
set_prolog_flag(user_error,_Error).
set_prolog_flag(user_error,_Error).
completions(S, Self) :-
@ -185,7 +170,7 @@ predicate(N,P,A) :-
cont(0, F, P, P0) :-
atom_concat( F, P, P0 ).
cont( _, F, P, PB ):-
atom_concat( [F, P, '('], PB ).
atom_concat( [F, P, '( )'], PB ).
ready(_Self, Line ) :-

View File

@ -3,15 +3,14 @@ import sys
import abc
import math
import itertools
import trace
from typing import Iterator, List, Tuple, Iterable, Union
from traitlets import Bool, Enum, observe, Int
try:
from yap4py.yapi import Engine, Goal, EngineArgs, PrologTableIter
except:
print("Could not load _yap dll.")
from yap4py.yapi import *
from yap_ipython.core.completer import Completer, Completion
from yap_ipython.utils.strdispatch import StrDispatch
# import yap_ipython.core
@ -32,12 +31,13 @@ bindvars = namedtuple('bindvars', 'list')
library = namedtuple('library', 'list')
v = namedtuple('_', 'slot')
load_files = namedtuple('load_files', 'file ofile args')
python_query= namedtuple('python_query', 'query_mgr string')
python_query = namedtuple('python_query', 'query_mgr string')
jupyter_query = namedtuple('jupyter_query', 'self text query')
enter_cell = namedtuple('enter_cell', 'self' )
exit_cell = namedtuple('exit_cell', 'self' )
completions = namedtuple('completions', 'txt self' )
errors = namedtuple('errors', 'self text' )
streams = namedtuple('streams', ' text' )
class YAPInputSplitter(InputSplitter):
@ -100,6 +100,7 @@ class YAPInputSplitter(InputSplitter):
Python line."""
t = self.physical_line_transforms + \
[self.assemble_logical_lines] + self.logical_line_transforms
return t
def engine(self, engine):
self.yapeng = engine
@ -107,11 +108,11 @@ class YAPInputSplitter(InputSplitter):
def validQuery(self, text, line=None):
"""Return whether a legal query
"""
if text == self.shell.os:
return True
if not line:
(_,line,_) = self.shell.prolog_cell(text)
line = line.strip().rstrip()
if not line:
return False
line = text.rstrip()
(line, _, _, _)=self.shell.clean_end(line)
self.errors = []
self.yapeng.mgoal(errors(self, line),"user")
return self.errors != []
@ -496,9 +497,11 @@ class YAPCompleter(Completer):
"""
self.matches = []
prolog_res = self.shell.yapeng.mgoal(completions(text, self), "user")
if self.matches:
return text, self.matches
magic_res = self.magic_matches(text)
return text, magic_res
return text, self.matches+magic_res
@ -509,8 +512,7 @@ class YAPRun:
self.shell = shell
self.yapeng = Engine()
self.yapeng.goal(use_module(library("jupyter")))
self.q = None
self.port = "call"
self.query = None
self.os = None
self.it = None
self.shell.yapeng = self.yapeng
@ -521,41 +523,58 @@ class YAPRun:
"""
if not text:
return []
if text == self.os:
return self.errors
self.errors=[]
(text,_,_,_) = self.clean_end(text)
self.yapeng.mgoal(errors(self,text),"user")
return self.errors
def jupyter_query(self, s):
#
# construct a self.query from a one-line string
# self.q is opaque to Python
program,query,mx = self.prolog_cell(s)
Found = False
if query != self.os:
self.os = None
self.iterations = 0
pg = jupyter_query( self, program, query)
self.it = Goal( self.yapeng, pg)
else:
mx += self.iterations
self.os = s
for answ in self.it:
found = True
self.bindings += [answ]
self.iterations += 1
if mx == self.iterations:
return True, self.bindings
port = self.it.port
if port == "exit":
self.q = None
self.os = None
return True,self.bindings
if port == "fail":
self.q = none
self.os = None
if self.bindings_message:
return True,self.bindings
# construct a self.queryuery from a one-line string
# self.query is opaque to Python
try:
program,query,stop,howmany = self.prolog_cell(s)
found = False
if s != self.os:
self.os = s
self.iterations = 0
self.bindings = []
pg = jupyter_query( self, program, query)
self.query = self.yapeng.query( pg)
self.query.port = "call"
else:
self.query.port = "retry"
self.os = s
howmany += self.iterations
while self.query.next():
answer = self.query.answer
found = True
self.bindings += [answer]
self.iterations += 1
if stop and howmany == self.iterations:
self.query.close()
self.query = None
self.os = None
return True, self.bindings
if self.query.port == "exit":
self.query.close()
self.query = None
self.os = None
sys.stderr.writeln('Done, with', self.bindings)
return True,self.bindings
self.query.close()
self.query = None
self.os = None
if self.bindings:
sys.stderr.write('Done, with', self.bindings, '\n')
else:
sys.stderr.write('Fail\n')
return True,{}
except Exception as e:
has_raised = True
self.result.result = False
def _yrun_cell(self, raw_cell, store_history=True, silent=False,
@ -573,7 +592,7 @@ class YAPRun:
IPython's machinery, this
should be set to False.
silent : bool
v If True, avoid side-effects, such as implicit displayhooks and
If True, avoid side-effects, such as implicit displayhooks and
and logging. silent=True forces store_history=False.
shell_futures : bool
If True, the code will share future statements with the interactive
@ -704,12 +723,31 @@ v If True, avoid side-effects, such as implicit displayhooks and
has_raised = False
try:
state = None
self.shell.bindings = dict = {}
if cell.strip():
state = self.jupyter_query( cell )
self.bindings = dicts = []
if cell.strip('\n \t'):
#create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
#ignoredirs=[sys.prefix, sys.exec_prefix],
trace=1,
count=0)
def f(self, cell):
self.jupyter_query( cell )
# run the new command using the given tracer
#
try:
self.yapeng.mgoal(streams(True),"user")
#state = tracer.runfunc(f,self,cell)
state = self.jupyter_query( cell )
self.yapeng.mgoal(streams(False),"user")
except Exception as e:
has_raised = True
self.yapeng.mgoal(streams("off"),"user")
if state:
self.shell.last_execution_succeeded = True
self.result.result = (True, dict)
self.result.result = (True, dicts)
else:
self.shell.last_execution_succeeded = True
self.result.result = (True, {})
@ -735,50 +773,49 @@ v If True, avoid side-effects, such as implicit displayhooks and
return self.result
def clean_end(self,s):
"""
Look at the query suffix and return
- whatever is left
- how much was taken
- whether to stop
- when to stop
"""
i = -1
try:
its = 0
j = 1
while s[i].isdigit():
ch = s[i]
its += j * (ord(ch) - ord('0'))
i-=1
j *= 10;
if s[i] == ';':
if j > 1 or its != 0:
return s[:i], 0 - i, True, its
return s[:i], 0 - i, False, 0
# one solution, stop
return s, 0, True, 1
except:
return s,0, False, 0
def prolog_cell(self,s):
"""
Trasform a text into program+query. A query is the
last line if the last line is non-empty and does not terminate
on a dot. You can also finish with
- `*`: you request all solutions
- '^': you want to check if there is an answer
- '?'[N]: you want an answer; optionally you want N answers
- `;`: you request all solutions
- ';'[N]: you want an answer; optionally you want N answers
If the line terminates on a `*/` or starts on a `%` we assume the line
is a comment.
"""
s = s.rstrip()
take = 0
its = 0
s0 = ''
for c in s:
if c == '\n' or c.isspace():
s0 += c
break
sf = ''
for c in reversed(s):
if c == '\n' or c.isspace():
sf += c
break
[program,x,query] = s.rpartition('\n')
if query == '':
query = program
while take < len(query):
take += 1
ch = query[-take]
if ch.isdigit():
its = its*10 + ord(ch) - ord('0')
elif ch == '*' and take == 1:
return program, query[:-take], -1
elif ch == '.' and take == 1:
return s, '', 1
elif ch == '/' and query[-2] == '*' and take == 1:
return program, query[:-take], 1
elif ch == '^' and take == 1:
return program, query[:-take], 1
elif ch == '?':
return program, query[:-take], its+1
else:
return program, query, 1
return s, '', 1
s0 = s.rstrip(' \n\t\i')
[program,x,query] = s0.rpartition('\n')
if query[-1] == '.':
return s,'',False,0
(query, _,loop, sols) = self.clean_end(query)
return (program, query, loop, sols)

View File

@ -428,12 +428,18 @@ load_files(Files,Opts) :-
'$lf'(Fs, Mod, Call, TOpts), fail;
true
).
'$lf'(user, Mod, _, TOpts) :- !,
b_setval('$user_source_file', user),
'$do_lf'(Mod, user_input, user_input, user_input, TOpts).
'$lf'(user_input, Mod, _, TOpts) :- !,
b_setval('$user_source_file', user_input),
'$do_lf'(Mod, user_input, user_input, user_input, TOpts).
'$lf'(user, Mod, Call, TOpts) :-
!,
stream_property( S, alias( user_input )),
'$set_lf_opt'('$from_stream', TOpts, true),
'$set_lf_opt'( stream , TOpts, S),
'$lf'(S, Mod, Call, TOpts).
'$lf'(user_input, Mod, Call, TOpts ) :-
!,
stream_property( S, alias( user_input )),
'$set_lf_opt'('$from_stream', TOpts, true),
'$set_lf_opt'( stream , TOpts, S),
'$lf'(S, Mod, Call, TOpts).
'$lf'(File, Mod, Call, TOpts) :-
'$lf_opt'(stream, TOpts, Stream),
b_setval('$user_source_file', File),
@ -453,7 +459,7 @@ load_files(Files,Opts) :-
'$start_lf'(If, Mod, Stream, TOpts, File, Y, Reexport, Imports),
close(Stream).
% consulting from a stre
% consulting from a stream
'$start_lf'(_not_loaded, Mod, Stream, TOpts, UserFile, File, _Reexport, _Imports) :-
'$lf_opt'('$from_stream', TOpts, true ),
!,
@ -650,7 +656,7 @@ db_files(Fs) :-
'$load_files'(Fs, [consult(db), if(not_loaded)], exo_files(Fs)).
'$csult'(Fs, M) :-
'$csult'(Fs, _M) :-
'$skip_list'(_, Fs ,L),
L \== [],
user:dot_qualified_goal(Fs),
@ -660,7 +666,7 @@ db_files(Fs) :-
'$load_files'(M:MFs,[],[M:Fs]).
'$csult'(Fs, M) :-
'$load_files'(M:Fs,[consult(consult)],[M:Fs]).
'$extract_minus'([], []).
'$extract_minus'([-F|Fs], [F|MFs]) :-
'$extract_minus'(Fs, MFs).
@ -1632,7 +1638,7 @@ End of conditional compilation.
consult_depth(LV) :- '$show_consult_level'(LV).
:- '$add_multifile'(Name,Arity,Module).
:- '$add_multifile'(dot_qualified_goal,2,user).
/**
@}