jupyter
This commit is contained in:
parent
31fd3eb344
commit
1a8c26b886
@ -2954,7 +2954,7 @@ yamop *Yap_PredIsIndexable(PredEntry *ap, UInt NSlots, yamop *next_pc) {
|
|||||||
if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) {
|
if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) {
|
||||||
CleanCls(&cint);
|
CleanCls(&cint);
|
||||||
Yap_Error(RESOURCE_ERROR_HEAP, TermNil, LOCAL_ErrorMessage);
|
Yap_Error(RESOURCE_ERROR_HEAP, TermNil, LOCAL_ErrorMessage);
|
||||||
return FAILCODE;
|
return NULL;
|
||||||
}
|
}
|
||||||
} else if (setjres == 4) {
|
} else if (setjres == 4) {
|
||||||
restore_machine_regs();
|
restore_machine_regs();
|
||||||
@ -2962,7 +2962,7 @@ yamop *Yap_PredIsIndexable(PredEntry *ap, UInt NSlots, yamop *next_pc) {
|
|||||||
if (!Yap_growtrail(LOCAL_Error_Size, FALSE)) {
|
if (!Yap_growtrail(LOCAL_Error_Size, FALSE)) {
|
||||||
CleanCls(&cint);
|
CleanCls(&cint);
|
||||||
Yap_Error(RESOURCE_ERROR_TRAIL, TermNil, LOCAL_ErrorMessage);
|
Yap_Error(RESOURCE_ERROR_TRAIL, TermNil, LOCAL_ErrorMessage);
|
||||||
return FAILCODE;
|
return NULL;
|
||||||
}
|
}
|
||||||
} else if (setjres != 0) {
|
} else if (setjres != 0) {
|
||||||
restore_machine_regs();
|
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)) {
|
if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) {
|
||||||
Yap_Error(RESOURCE_ERROR_HEAP, TermNil, LOCAL_ErrorMessage);
|
Yap_Error(RESOURCE_ERROR_HEAP, TermNil, LOCAL_ErrorMessage);
|
||||||
CleanCls(&cint);
|
CleanCls(&cint);
|
||||||
return FAILCODE;
|
return NULL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
restart_index:
|
restart_index:
|
||||||
@ -2983,7 +2983,7 @@ restart_index:
|
|||||||
if (compile_index(&cint) == (UInt)FAILCODE) {
|
if (compile_index(&cint) == (UInt)FAILCODE) {
|
||||||
Yap_ReleaseCMem(&cint);
|
Yap_ReleaseCMem(&cint);
|
||||||
CleanCls(&cint);
|
CleanCls(&cint);
|
||||||
return FAILCODE;
|
return NULL;
|
||||||
}
|
}
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
if (GLOBAL_Option['i' - 'a' + 1]) {
|
if (GLOBAL_Option['i' - 'a' + 1]) {
|
||||||
|
@ -689,10 +689,10 @@ if (PYTHONLIBS_FOUND AND SWIG_FOUND)
|
|||||||
find_python_module(wheel)
|
find_python_module(wheel)
|
||||||
find_python_module(setuptools)
|
find_python_module(setuptools)
|
||||||
find_python_module(backcall)
|
find_python_module(backcall)
|
||||||
|
|
||||||
if (PY_JUPYTER AND PY_WHEEL AND PY_SETUPTOOLS AND PY_BACKCALL)
|
if (PY_JUPYTER AND PY_WHEEL AND PY_SETUPTOOLS AND PY_BACKCALL)
|
||||||
add_subdirectory(packages/python/yap_kernel)
|
add_subdirectory(packages/python/yap_kernel)
|
||||||
ENDIF ()
|
ENDIF ()
|
||||||
|
|
||||||
endif ()
|
endif ()
|
||||||
|
|
||||||
|
|
||||||
|
39
CXX/yapi.cpp
39
CXX/yapi.cpp
@ -239,10 +239,10 @@ Term &YAPTerm::operator[](arity_t i) {
|
|||||||
tf = TailOfTerm(t0);
|
tf = TailOfTerm(t0);
|
||||||
RECOVER_MACHINE_REGS();
|
RECOVER_MACHINE_REGS();
|
||||||
tf = RepPair(tf)[i];
|
tf = RepPair(tf)[i];
|
||||||
|
} else {
|
||||||
|
Yap_Error(TYPE_ERROR_COMPOUND, t0, "");
|
||||||
}
|
}
|
||||||
RECOVER_MACHINE_REGS();
|
RECOVER_MACHINE_REGS();
|
||||||
Yap_Error(TYPE_ERROR_COMPOUND, tf, "");
|
|
||||||
throw YAPError();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Term &YAPListTerm::operator[](arity_t i) {
|
Term &YAPListTerm::operator[](arity_t i) {
|
||||||
@ -377,8 +377,7 @@ Term YAPListTerm::car() {
|
|||||||
return (HeadOfTerm(to));
|
return (HeadOfTerm(to));
|
||||||
else {
|
else {
|
||||||
Yap_Error(TYPE_ERROR_LIST, to, "");
|
Yap_Error(TYPE_ERROR_LIST, to, "");
|
||||||
return 0;
|
return TermUnique;
|
||||||
throw YAPError();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -432,8 +431,8 @@ bool YAPEngine::call(YAPPredicate ap, YAPTerm ts[]) {
|
|||||||
// allow Prolog style exceotion handling
|
// allow Prolog style exceotion handling
|
||||||
LOCAL_RestartEnv = &buf;
|
LOCAL_RestartEnv = &buf;
|
||||||
if (sigsetjmp(*LOCAL_RestartEnv, false)) {
|
if (sigsetjmp(*LOCAL_RestartEnv, false)) {
|
||||||
return 0;
|
std::cerr << "Restart\n";
|
||||||
throw YAPError();
|
//q.e = new YAPError();
|
||||||
}
|
}
|
||||||
// don't forget, on success these bindings will still be there);
|
// don't forget, on success these bindings will still be there);
|
||||||
result = YAP_LeaveGoal(false, &q);
|
result = YAP_LeaveGoal(false, &q);
|
||||||
@ -447,8 +446,7 @@ bool YAPEngine::call(YAPPredicate ap, YAPTerm ts[]) {
|
|||||||
std::cerr << "Exception received by "
|
std::cerr << "Exception received by "
|
||||||
<< YAPApplTerm(ap.functor(), ts).text() << ".\n Forwarded...\n\n";
|
<< YAPApplTerm(ap.functor(), ts).text() << ".\n Forwarded...\n\n";
|
||||||
LOCAL_RestartEnv = oj;
|
LOCAL_RestartEnv = oj;
|
||||||
return 0;
|
return false;
|
||||||
throw e;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -480,8 +478,8 @@ bool YAPEngine::mgoal(Term t, Term tmod) {
|
|||||||
// allow Prolog style exception handling
|
// allow Prolog style exception handling
|
||||||
LOCAL_RestartEnv = &buf;
|
LOCAL_RestartEnv = &buf;
|
||||||
if (sigsetjmp(*LOCAL_RestartEnv, false)) {
|
if (sigsetjmp(*LOCAL_RestartEnv, false)) {
|
||||||
return false;
|
std::cerr << "Restart\n";
|
||||||
//throw YAPError();
|
//throw new YAPError();
|
||||||
}
|
}
|
||||||
// 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 ");
|
||||||
@ -557,7 +555,7 @@ Term YAPEngine::fun(Term t) {
|
|||||||
sigjmp_buf buf, *oldp = LOCAL_RestartEnv;
|
sigjmp_buf buf, *oldp = LOCAL_RestartEnv;
|
||||||
LOCAL_RestartEnv = &buf;
|
LOCAL_RestartEnv = &buf;
|
||||||
if (sigsetjmp(*LOCAL_RestartEnv, false)) {
|
if (sigsetjmp(*LOCAL_RestartEnv, false)) {
|
||||||
// throw YAPError();
|
// throw new YAPError();
|
||||||
LOCAL_RestartEnv = oldp;
|
LOCAL_RestartEnv = oldp;
|
||||||
RECOVER_MACHINE_REGS();
|
RECOVER_MACHINE_REGS();
|
||||||
return 0;
|
return 0;
|
||||||
@ -676,14 +674,14 @@ bool YAPQuery::next() {
|
|||||||
bool result = false;
|
bool result = false;
|
||||||
sigjmp_buf buf, *oldp = LOCAL_RestartEnv;
|
sigjmp_buf buf, *oldp = LOCAL_RestartEnv;
|
||||||
Term terr;
|
Term terr;
|
||||||
|
e = nullptr;
|
||||||
try {
|
try {
|
||||||
BACKUP_MACHINE_REGS();
|
BACKUP_MACHINE_REGS();
|
||||||
if (!q_open)
|
if (!q_open)
|
||||||
return false;
|
return false;
|
||||||
LOCAL_RestartEnv = &buf;
|
LOCAL_RestartEnv = &buf;
|
||||||
if (sigsetjmp(*LOCAL_RestartEnv, false)) {
|
if (sigsetjmp(*LOCAL_RestartEnv, false)) {
|
||||||
// throw YAPError();
|
//e = new YAPError();
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
// 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 ");
|
||||||
@ -701,11 +699,10 @@ bool YAPQuery::next() {
|
|||||||
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "fail");
|
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "fail");
|
||||||
}
|
}
|
||||||
q_state = 1;
|
q_state = 1;
|
||||||
if ((terr = Yap_GetException())) {
|
if ((terr = Yap_PeekException())) {
|
||||||
if ((terr = Yap_GetException())) {
|
|
||||||
LOCAL_RestartEnv = &buf;
|
LOCAL_RestartEnv = &buf;
|
||||||
throw YAPError();
|
|
||||||
}
|
result = false;
|
||||||
}
|
}
|
||||||
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "out %d", result);
|
__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) {
|
void YAPEngine::doInit(YAP_file_type_t BootMode, YAPEngineArgs *engineArgs) {
|
||||||
if ((BootMode = YAP_Init(engineArgs)) == YAP_FOUND_BOOT_ERROR) {
|
if ((BootMode = YAP_Init(engineArgs)) == YAP_FOUND_BOOT_ERROR) {
|
||||||
|
std::cerr << "Exception received by " << __func__ << "( "
|
||||||
|
<< "while booting" << ").\n Forwarded...\n\n";
|
||||||
return;
|
return;
|
||||||
throw YAPError();
|
|
||||||
}
|
}
|
||||||
/* Begin preprocessor code */
|
/* Begin preprocessor code */
|
||||||
/* live */
|
/* live */
|
||||||
@ -903,7 +901,8 @@ PredEntry *YAPPredicate::getPred(YAPTerm &tt, CELL *&outp) {
|
|||||||
Yap_ThrowError(INSTANTIATION_ERROR, tt.term(), 0);
|
Yap_ThrowError(INSTANTIATION_ERROR, tt.term(), 0);
|
||||||
else if (IsNumTerm(t))
|
else if (IsNumTerm(t))
|
||||||
Yap_ThrowError(TYPE_ERROR_CALLABLE, tt.term(), 0);
|
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);
|
tt.put(t);
|
||||||
if (IsAtomTerm(t)) {
|
if (IsAtomTerm(t)) {
|
||||||
@ -1062,7 +1061,7 @@ Term YAPEngine::top_level(std::string s) {
|
|||||||
ARG2 = tp;
|
ARG2 = tp;
|
||||||
ARG3 = MkVarTerm();
|
ARG3 = MkVarTerm();
|
||||||
if (ARG1 == 0)
|
if (ARG1 == 0)
|
||||||
YAPError(SYNTAX_ERROR);
|
Yap_Error(SYNTAX_ERROR, ARG1, "in input query");
|
||||||
YAPPredicate p = YAPPredicate(YAP_TopGoal());
|
YAPPredicate p = YAPPredicate(YAP_TopGoal());
|
||||||
YAPQuery *Q = new YAPQuery(p, 0);
|
YAPQuery *Q = new YAPQuery(p, 0);
|
||||||
Term ts[2];
|
Term ts[2];
|
||||||
|
@ -34,7 +34,11 @@ class X_API YAPError {
|
|||||||
|
|
||||||
public:
|
public:
|
||||||
YAPError(){
|
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
|
/// error handler object with initial data when receiving the error term
|
||||||
YAPError(yap_error_number id, YAPTerm culprit, std::string txt);
|
YAPError(yap_error_number id, YAPTerm culprit, std::string txt);
|
||||||
|
@ -46,6 +46,7 @@ class X_API YAPQuery : public YAPPredicate {
|
|||||||
YAPTerm goal;
|
YAPTerm goal;
|
||||||
// temporaries
|
// temporaries
|
||||||
Term tnames, tgoal;
|
Term tnames, tgoal;
|
||||||
|
YAPError *e;
|
||||||
|
|
||||||
inline void setNext() { // oq = LOCAL_execution;
|
inline void setNext() { // oq = LOCAL_execution;
|
||||||
// LOCAL_execution = this;
|
// LOCAL_execution = this;
|
||||||
@ -292,6 +293,7 @@ private:
|
|||||||
YAPError yerror;
|
YAPError yerror;
|
||||||
void doInit(YAP_file_type_t BootMode, YAPEngineArgs *cargs);
|
void doInit(YAP_file_type_t BootMode, YAPEngineArgs *cargs);
|
||||||
YAP_dogoalinfo q;
|
YAP_dogoalinfo q;
|
||||||
|
YAPError e;
|
||||||
PredEntry *rewriteUndefEngineQuery(PredEntry *ap, Term &t, Term tmod);
|
PredEntry *rewriteUndefEngineQuery(PredEntry *ap, Term &t, Term tmod);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
@ -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
|
#ifndef LOCAL
|
||||||
#include "Yap.h"
|
#include "Yap.h"
|
||||||
#include "heap.h"
|
#include "heap.h"
|
||||||
@ -17,6 +17,7 @@
|
|||||||
#define LOCAL_INIT_RESTORE(A,B,C,D) A B; C; D;
|
#define LOCAL_INIT_RESTORE(A,B,C,D) A B; C; D;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
/// Current bindings for std streams, includes default s
|
||||||
LOCAL_INIT(int, c_input_stream, 0);
|
LOCAL_INIT(int, c_input_stream, 0);
|
||||||
LOCAL_INIT(int, c_output_stream, 1);
|
LOCAL_INIT(int, c_output_stream, 1);
|
||||||
LOCAL_INIT(int, c_error_stream, 2);
|
LOCAL_INIT(int, c_error_stream, 2);
|
||||||
|
@ -4,7 +4,7 @@ option(WITH_JAVA "Try to use Java (currently Java 6,7,8)" ON)
|
|||||||
if (WITH_JAVA)
|
if (WITH_JAVA)
|
||||||
#detect java setup, as it is shared between different installations.
|
#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 Development)
|
||||||
# find_package(Java COMPONENTS Runtime)
|
# find_package(Java COMPONENTS Runtime)
|
||||||
#find_package(JavaLibs)
|
#find_package(JavaLibs)
|
||||||
|
@ -422,19 +422,19 @@
|
|||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"\n",
|
"\n",
|
||||||
"main :- \n",
|
"main :- \n",
|
||||||
" := import( matplotlib.pyplot ),\n",
|
" import( matplotlib.pyplot ),\n",
|
||||||
" := import( numpy ),\n",
|
" import( numpy ),\n",
|
||||||
" Plt = matplotlib.pyplot,\n",
|
" Plt := matplotlib.pyplot,\n",
|
||||||
" Np = numpy,\n",
|
" Np := numpy,\n",
|
||||||
" t := Np.arange(0.0, 2.0, 0.01),\n",
|
" t := np.arange(0.0, 2.0, 0.01),\n",
|
||||||
" s := 1 + Np.sin(2*Np.pi*t),\n",
|
" s := 1 + np.sin(2*np.pi*t),\n",
|
||||||
" := Plt.plot(t, s),\n",
|
" Plt.plot(t, s),\n",
|
||||||
" := Plt.xlabel(`time (s)`),\n",
|
" Plt.xlabel(`time (s)`),\n",
|
||||||
" := Plt.ylabel(`voltage (mV)`),\n",
|
" Plt.ylabel(`voltage (mV)`),\n",
|
||||||
" := Plt.title(`About as simple as it gets, folks`),\n",
|
" Plt.title(`About as simple as it gets, folks`),\n",
|
||||||
" := Plt.grid(true),\n",
|
" Plt.grid(true),\n",
|
||||||
" := Plt.savefig(`test2.png`),\n",
|
" Plt.savefig(`test2.png`),\n",
|
||||||
" := Plt.show().\n",
|
" Plt.show().\n",
|
||||||
"\n",
|
"\n",
|
||||||
"main"
|
"main"
|
||||||
]
|
]
|
||||||
|
@ -1848,7 +1848,6 @@ static Int close2(USES_REGS1) { /* '$close'(+GLOBAL_Stream) */
|
|||||||
Yap_Error(LOCAL_Error_TYPE, tlist, NULL);
|
Yap_Error(LOCAL_Error_TYPE, tlist, NULL);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
return FALSE;
|
|
||||||
}
|
}
|
||||||
// if (args[CLOSE_FORCE].used) {
|
// if (args[CLOSE_FORCE].used) {
|
||||||
// }
|
// }
|
||||||
|
@ -268,6 +268,7 @@ static Term scanToList(TokEntry *tok, TokEntry *errtok) {
|
|||||||
}
|
}
|
||||||
tok = tok->TokNext;
|
tok = tok->TokNext;
|
||||||
}
|
}
|
||||||
|
if (ts[0])
|
||||||
Yap_DebugPlWriteln(ts[0]);
|
Yap_DebugPlWriteln(ts[0]);
|
||||||
return 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 tokptr: the sequence of tokens
|
||||||
* @par sno: the stream numbet
|
* @par sno: the stream numbet
|
||||||
|
@ -1005,10 +1005,6 @@ static void CloseStream(int sno) {
|
|||||||
} else if (GLOBAL_Stream[sno].status & (InMemory_Stream_f)) {
|
} else if (GLOBAL_Stream[sno].status & (InMemory_Stream_f)) {
|
||||||
Yap_CloseMemoryStream(sno);
|
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;
|
LOCAL_c_input_stream = StdInStream;
|
||||||
}
|
}
|
||||||
@ -1018,6 +1014,11 @@ static void CloseStream(int sno) {
|
|||||||
if (LOCAL_c_error_stream == sno) {
|
if (LOCAL_c_error_stream == sno) {
|
||||||
LOCAL_c_error_stream = StdErrStream;
|
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) {
|
/* if (st->status == Socket_Stream_f|Input_Stream_f|Output_Stream_f) {
|
||||||
Yap_CloseSocket();
|
Yap_CloseSocket();
|
||||||
}
|
}
|
||||||
|
@ -728,7 +728,7 @@ def gecode_version():
|
|||||||
os.remove(file_hh)
|
os.remove(file_hh)
|
||||||
os.remove(file_txt)
|
os.remove(file_txt)
|
||||||
else:
|
else:
|
||||||
version = "5.0.0"
|
version = "6.0.0"
|
||||||
GECODE_VERSION = version
|
GECODE_VERSION = version
|
||||||
return version
|
return version
|
||||||
|
|
||||||
|
@ -664,8 +664,8 @@ static void Yap_InitBackMYDDAS_SQLITE3Preds(void) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
X_API void init_sqlite3(void) {
|
X_API void init_sqlite3(void) {
|
||||||
// Yap_InitMYDDAS_SQLITE3Preds();
|
Yap_InitMYDDAS_SQLITE3Preds();
|
||||||
// Yap_InitBackMYDDAS_SQLITE3Preds();
|
Yap_InitBackMYDDAS_SQLITE3Preds();
|
||||||
}
|
}
|
||||||
|
|
||||||
#if _ANDROID_
|
#if _ANDROID_
|
||||||
|
@ -35,6 +35,7 @@ static PyObject *s_to_python(const char *s, bool eval, PyObject *p0) {
|
|||||||
// char *ns = Py_Malloc(strlen(s)+1);
|
// char *ns = Py_Malloc(strlen(s)+1);
|
||||||
/// strcpy(ns,s);
|
/// strcpy(ns,s);
|
||||||
PyObject *pobj = PyUnicode_FromString(s);
|
PyObject *pobj = PyUnicode_FromString(s);
|
||||||
|
Py_INCREF(pobj);
|
||||||
return 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
|
* @return a Python object descriptor or NULL if failed
|
||||||
*/
|
*/
|
||||||
X_API PyObject *string_to_python(const char *s, bool eval, PyObject *p0) {
|
X_API PyObject *string_to_python(const char *s, bool eval, PyObject *p0) {
|
||||||
|
|
||||||
|
|
||||||
char *buf = malloc(strlen(s) + 1), *child;
|
char *buf = malloc(strlen(s) + 1), *child;
|
||||||
while ((child = strchr(s, '.')) != NULL) {
|
while ((child = strchr(s, '.')) != NULL) {
|
||||||
size_t len = child - s;
|
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);
|
AOK(PL_get_arg(1, t, t), NULL);
|
||||||
if (!(dict = PyDict_New()))
|
if (!(dict = PyDict_New()))
|
||||||
return NULL;
|
return NULL;
|
||||||
|
Py_INCREF(dict);
|
||||||
DebugPrintf("Dict %p\n", dict);
|
DebugPrintf("Dict %p\n", dict);
|
||||||
|
|
||||||
while (PL_is_functor(t, FUNCTOR_comma2)) {
|
while (PL_is_functor(t, FUNCTOR_comma2)) {
|
||||||
|
@ -46,6 +46,7 @@ foreign_t assign_to_symbol(term_t t, PyObject *e) {
|
|||||||
PyObject *dic;
|
PyObject *dic;
|
||||||
if (!lookupPySymbol(s, NULL, &dic))
|
if (!lookupPySymbol(s, NULL, &dic))
|
||||||
dic = py_Main;
|
dic = py_Main;
|
||||||
|
Py_INCREF(e);
|
||||||
return PyObject_SetAttrString(dic, s, e) == 0;
|
return PyObject_SetAttrString(dic, s, e) == 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -319,9 +320,10 @@ bool python_assign(term_t t, PyObject *exp, PyObject *context) {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
if (PyDict_Check(o)) {
|
if (PyDict_Check(o)) {
|
||||||
if (PyDict_SetItem(o, i, exp) == 0)
|
if (PyDict_SetItem(o, i, exp) == 0) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if (PyObject_SetAttr(o, i, exp) == 0) {
|
if (PyObject_SetAttr(o, i, exp) == 0) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@ -35,7 +35,7 @@
|
|||||||
|
|
||||||
PyObject *find_obj(PyObject *ob, term_t lhs, bool eval);
|
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)
|
#define DebugPrintf(s, op) fprintf(stderr, "%s:%d: " s, __FILE__, __LINE__, op)
|
||||||
#else
|
#else
|
||||||
#define DebugPrintf(s, op)
|
#define DebugPrintf(s, op)
|
||||||
@ -85,7 +85,7 @@ extern PyObject *py_ModDict;
|
|||||||
|
|
||||||
extern X_API bool python_in_python;
|
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);
|
extern term_t python_acquire_GIL(void);
|
||||||
|
|
||||||
static inline Py_ssize_t get_p_int(PyObject *o, Py_ssize_t def) {
|
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_pyeval(term_t t, PyObject *context, bool cvt);
|
||||||
extern PyObject *compound_to_pytree(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);
|
bool eval_atom);
|
||||||
|
|
||||||
extern PyObject *term_to_nametuple(const char *s, arity_t arity, PyObject *);
|
extern PyObject *term_to_nametuple(const char *s, arity_t arity, PyObject *);
|
||||||
|
@ -1014,7 +1014,6 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) {
|
|||||||
} else {
|
} else {
|
||||||
char *s = PL_atom_chars(name);
|
char *s = PL_atom_chars(name);
|
||||||
PyObject *ys = lookupPySymbol(s, o, NULL), *pArgs;
|
PyObject *ys = lookupPySymbol(s, o, NULL), *pArgs;
|
||||||
DebugPrintf("Tuple %p\n", pArgs);
|
|
||||||
int i;
|
int i;
|
||||||
term_t tleft = PL_new_term_ref();
|
term_t tleft = PL_new_term_ref();
|
||||||
bool indict = true;
|
bool indict = true;
|
||||||
@ -1037,6 +1036,7 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) {
|
|||||||
pArgs = PyTuple_New(i);
|
pArgs = PyTuple_New(i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
DebugPrintf("Tuple %p\n", pyDict);
|
||||||
if (!indict) {
|
if (!indict) {
|
||||||
if (PL_is_variable(tleft)) {
|
if (PL_is_variable(tleft)) {
|
||||||
pArg = Py_None;
|
pArg = Py_None;
|
||||||
|
@ -5,10 +5,45 @@
|
|||||||
|
|
||||||
#include "YapStreams.h"
|
#include "YapStreams.h"
|
||||||
|
|
||||||
VFS_t pystream;
|
YAP_Term TermErrStream, TermOutStream;
|
||||||
|
|
||||||
static void *py_open(VFS_t *me, int sno, const char *name,
|
static int py_put(int sno, int ch)
|
||||||
const char *io_mode) {
|
{
|
||||||
|
// 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 HAVE_STRCASESTR
|
||||||
if (strcasestr(name, "/python/") == name)
|
if (strcasestr(name, "/python/") == name)
|
||||||
name += strlen("/python/");
|
name += strlen("/python/");
|
||||||
@ -17,68 +52,111 @@ static void *py_open(VFS_t *me, int sno, const char *name,
|
|||||||
name += strlen("/python/");
|
name += strlen("/python/");
|
||||||
#endif
|
#endif
|
||||||
StreamDesc *st = YAP_RepStreamFromId(sno);
|
StreamDesc *st = YAP_RepStreamFromId(sno);
|
||||||
|
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.
|
// we assume object is already open, so there is no need to open it.
|
||||||
PyObject *stream = string_to_python(name, true, NULL);
|
PyObject *pystream = string_to_python(name, true, NULL);
|
||||||
if (stream == Py_None)
|
if (pystream == Py_None) {
|
||||||
return NULL;
|
return NULL;
|
||||||
Py_INCREF(stream);
|
} else {
|
||||||
st->u.private_data = stream;
|
st->u.private_data = pystream;
|
||||||
st->vfs = me;
|
st->vfs = me;
|
||||||
st->name = YAP_LookupAtom(name);
|
st->name = YAP_LookupAtom(name);
|
||||||
st->user_name = YAP_MkAtomTerm(st->name);
|
st->user_name = YAP_MkAtomTerm(st->name);
|
||||||
return stream;
|
}
|
||||||
|
}
|
||||||
|
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) {
|
static bool getLine(int inp) {
|
||||||
// PyObject *pyw; // buffer
|
char *myrl_line = NULL;
|
||||||
// int pyw_kind;
|
StreamDesc *rl_instream = YAP_RepStreamFromId(inp);
|
||||||
// PyObject *pyw_data;
|
PyObject*prompt = PyUnicode_FromString( "?- "),
|
||||||
// PySys_WriteStdout("%C", ch);
|
*msg = PyUnicode_FromString("");
|
||||||
// return ch;
|
/* window of vulnerability opened */
|
||||||
char s[2];
|
myrl_line = PyUnicode_AsUTF8(PyObject_CallFunctionObjArgs(rl_instream->u.private_data,msg,prompt,NULL));
|
||||||
StreamDesc *st = YAP_GetStreamFromId(sno);
|
rl_instream->u.irl.ptr = rl_instream->u.irl.buf = (const unsigned char*)myrl_line;
|
||||||
// PyUnicode_WRITE(pyw_kind, pyw_data, 0, ch);
|
myrl_line = NULL;
|
||||||
PyObject *err, *fput = PyObject_GetAttrString(st->u.private_data, "write");
|
return true;
|
||||||
s[0] = ch;
|
}
|
||||||
s[1] = '\0';
|
|
||||||
PyObject_CallMethodObjArgs(st->u.private_data, PyUnicode_FromString("write"),
|
|
||||||
PyUnicode_FromString(s), NULL);
|
static int py_getc(int sno) {
|
||||||
if ((err = PyErr_Occurred())) {
|
StreamDesc *s = YAP_RepStreamFromId(sno);
|
||||||
PyErr_SetString(
|
int ch;
|
||||||
err,
|
bool fetch = (s->u.irl.buf == NULL);
|
||||||
"Error in put\n"); // %s:%s:%d!\n", __FILE__, __FUNCTION__, __LINE__);
|
|
||||||
|
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;
|
return ch;
|
||||||
}
|
}
|
||||||
|
|
||||||
static int py_get(int sno) {
|
/**
|
||||||
StreamDesc *s = YAP_GetStreamFromId(sno);
|
@brief Yap_ReadlinePeekChar peeks the next char from the
|
||||||
PyObject *fget = PyObject_GetAttrString(s->u.private_data, "read");
|
readline buffer, but does not actually grab it.
|
||||||
PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL);
|
|
||||||
return PyUnicode_READ_CHAR(pyr, 0);
|
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_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) {
|
static int64_t py_seek(int sno, int64_t where, int how) {
|
||||||
StreamDesc *s = YAP_GetStreamFromId(sno);
|
StreamDesc *g0 = YAP_RepStreamFromId(sno);
|
||||||
PyObject *fseek = PyObject_GetAttrString(s->u.private_data, "seek");
|
PyGILState_STATE s0 = python_acquire_GIL();
|
||||||
|
PyObject *fseek = PyObject_GetAttrString(g0->u.private_data, "seek");
|
||||||
PyObject *pyr = PyObject_CallFunctionObjArgs(fseek, PyLong_FromLong(where),
|
PyObject *pyr = PyObject_CallFunctionObjArgs(fseek, PyLong_FromLong(where),
|
||||||
PyLong_FromLong(how), NULL);
|
PyLong_FromLong(how), NULL);
|
||||||
|
python_release_GIL(s0);
|
||||||
return PyLong_AsLong(pyr);
|
return PyLong_AsLong(pyr);
|
||||||
}
|
}
|
||||||
|
|
||||||
static void py_flush(int sno) {
|
static void py_flush(int sno) {
|
||||||
StreamDesc *s = YAP_GetStreamFromId(sno);
|
StreamDesc *s = YAP_GetStreamFromId(sno);
|
||||||
|
YAP_Term tg = python_acquire_GIL();
|
||||||
PyObject *flush = PyObject_GetAttrString(s->u.private_data, "flush");
|
PyObject *flush = PyObject_GetAttrString(s->u.private_data, "flush");
|
||||||
PyObject_CallFunction(flush, NULL);
|
PyObject_CallFunction(flush, NULL);
|
||||||
|
python_release_GIL(tg);
|
||||||
}
|
}
|
||||||
|
|
||||||
#if 0
|
#if 0
|
||||||
@ -110,13 +188,15 @@ bool init_python_vfs(void) {
|
|||||||
pystream.suffix = NULL;
|
pystream.suffix = NULL;
|
||||||
pystream.open = py_open;
|
pystream.open = py_open;
|
||||||
pystream.close = py_close;
|
pystream.close = py_close;
|
||||||
pystream.get_char = py_get;
|
pystream.get_char = py_getc;
|
||||||
pystream.peek_char = py_peek;
|
pystream.peek_char = py_peek;
|
||||||
pystream.put_char = py_put;
|
pystream.put_char = py_put;
|
||||||
pystream.flush = py_flush;
|
pystream.flush = py_flush;
|
||||||
pystream.seek = py_seek;
|
pystream.seek = py_seek;
|
||||||
pystream.next = GLOBAL_VFS;
|
pystream.next = GLOBAL_VFS;
|
||||||
GLOBAL_VFS = &pystream;
|
GLOBAL_VFS = &pystream;
|
||||||
|
TermOutStream = YAP_MkAtomTerm(YAP_LookupAtom("std.output"));
|
||||||
|
TermErrStream = YAP_MkAtomTerm(YAP_LookupAtom("std.error"));
|
||||||
// NULL;
|
// NULL;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@ -631,9 +631,9 @@ static YAP_Int p_python_threaded(void) {
|
|||||||
pyErrorAndReturn(true, false);
|
pyErrorAndReturn(true, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
static PyGILState_STATE gstate;
|
|
||||||
|
|
||||||
term_t python_acquire_GIL(void) {
|
term_t python_acquire_GIL(void) {
|
||||||
|
static PyGILState_STATE gstate;
|
||||||
term_t curSlot = PL_new_term_ref();
|
term_t curSlot = PL_new_term_ref();
|
||||||
if (!_threaded)
|
if (!_threaded)
|
||||||
pyErrorAndReturn(curSlot, false);
|
pyErrorAndReturn(curSlot, false);
|
||||||
@ -643,15 +643,18 @@ term_t python_acquire_GIL(void) {
|
|||||||
// if (_locked > 0) { _locked++ ; }
|
// if (_locked > 0) { _locked++ ; }
|
||||||
// else
|
// else
|
||||||
gstate = PyGILState_Ensure();
|
gstate = PyGILState_Ensure();
|
||||||
|
PL_put_integer(curSlot, gstate);
|
||||||
pyErrorAndReturn(curSlot, false);
|
pyErrorAndReturn(curSlot, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool python_release_GIL(term_t curBlock) {
|
bool python_release_GIL(term_t curBlock) {
|
||||||
|
PyGILState_STATE gstate;
|
||||||
PyErr_Clear();
|
PyErr_Clear();
|
||||||
PL_reset_term_refs(curBlock);
|
|
||||||
if (_threaded) {
|
if (_threaded) {
|
||||||
|
PL_get_integer(curBlock, &gstate);
|
||||||
PyGILState_Release(gstate);
|
PyGILState_Release(gstate);
|
||||||
}
|
}
|
||||||
|
PL_reset_term_refs(curBlock);
|
||||||
pyErrorAndReturn(true, false);
|
pyErrorAndReturn(true, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -134,7 +134,7 @@ user(P1,P2) :- !,
|
|||||||
:= P1,
|
:= P1,
|
||||||
:= P2.
|
:= P2.
|
||||||
|
|
||||||
user:(:= ) :- catch( python:python_proc(F), _, fail ).
|
user:(:= F) :- catch( python:python_proc(F), _, fail ).
|
||||||
|
|
||||||
user:( V := F ) :-
|
user:( V := F ) :-
|
||||||
python:python_assign(F, V).
|
python:python_assign(F, V).
|
||||||
|
@ -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 CPLUSPLUS ON)
|
||||||
SET_SOURCE_FILES_PROPERTIES(../../swig/yap.i PROPERTIES SWIG_FLAGS "-O;-py3")
|
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)
|
#SET_SOURCE_FILES_PROPERTIES(../../swi/yap.i PROPERTIES OUTPUT_NAME yap)
|
||||||
|
|
||||||
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap4py)
|
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap4py)
|
||||||
|
|
||||||
set(YAP4PY_PL prolog/yapi.yap)
|
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("setup.py.in" setup.py)
|
||||||
configure_file("MANIFEST.in" ${CMAKE_CURRENT_BINARY_DIR}/MANIFEST.in)
|
configure_file("MANIFEST.in" ${CMAKE_CURRENT_BINARY_DIR}/MANIFEST.in)
|
||||||
|
@ -10,9 +10,8 @@
|
|||||||
python_query/2,
|
python_query/2,
|
||||||
yapi_query/2
|
yapi_query/2
|
||||||
]).
|
]).
|
||||||
:- stop_low_level_trace.
|
|
||||||
|
|
||||||
:- yap_flag(verbose, verbose).
|
:- yap_flag(verbose, silent).
|
||||||
|
|
||||||
|
|
||||||
:- use_module( library(lists) ).
|
:- use_module( library(lists) ).
|
||||||
@ -22,6 +21,7 @@
|
|||||||
:- reexport( library(python) ).
|
:- reexport( library(python) ).
|
||||||
|
|
||||||
:- python_import(yap4py.yapi).
|
:- python_import(yap4py.yapi).
|
||||||
|
:- python_import(gc).
|
||||||
|
|
||||||
%:- start_low_level_trace.
|
%:- start_low_level_trace.
|
||||||
|
|
||||||
@ -38,6 +38,7 @@
|
|||||||
%:- initialization set_preds.
|
%:- initialization set_preds.
|
||||||
|
|
||||||
set_preds :-
|
set_preds :-
|
||||||
|
fail,
|
||||||
current_predicate(P, Q),
|
current_predicate(P, Q),
|
||||||
functor(Q,P,A),
|
functor(Q,P,A),
|
||||||
atom_string(P,S),
|
atom_string(P,S),
|
||||||
@ -47,6 +48,7 @@ set_preds :-
|
|||||||
fail),
|
fail),
|
||||||
fail.
|
fail.
|
||||||
set_preds :-
|
set_preds :-
|
||||||
|
fail,
|
||||||
system_predicate(P/A),
|
system_predicate(P/A),
|
||||||
atom_string(P,S),
|
atom_string(P,S),
|
||||||
catch(
|
catch(
|
||||||
@ -61,14 +63,15 @@ argi(N,I,I1) :-
|
|||||||
I1 is I+1.
|
I1 is I+1.
|
||||||
|
|
||||||
python_query( Caller, String ) :-
|
python_query( Caller, String ) :-
|
||||||
Self := Caller.it,
|
|
||||||
atomic_to_term( String, Goal, VarNames ),
|
atomic_to_term( String, Goal, VarNames ),
|
||||||
query_to_answer( Goal, VarNames, Status, Bindings),
|
query_to_answer( Goal, VarNames, Status, Bindings),
|
||||||
Self.port := Status,
|
Caller.port := Status,
|
||||||
|
% := print( gc.get_referrers(Caller.port)),
|
||||||
write_query_answer( Bindings ),
|
write_query_answer( Bindings ),
|
||||||
nl(user_error),
|
nl(user_error),
|
||||||
Self.bindings := {},
|
Caller.answer := {},
|
||||||
maplist(in_dict(Self.bindings), Bindings).
|
maplist(in_dict(Caller.answer), Bindings).
|
||||||
|
% := print( "b", gc.get_referrers(Caller.answer)).
|
||||||
|
|
||||||
in_dict(Dict, var([V0,V|Vs])) :- !,
|
in_dict(Dict, var([V0,V|Vs])) :- !,
|
||||||
Dict[V] := V0,
|
Dict[V] := V0,
|
||||||
|
@ -51,24 +51,25 @@ from distutils.core import setup
|
|||||||
|
|
||||||
here = abspath(dirname(__file__))
|
here = abspath(dirname(__file__))
|
||||||
libpydir = abspath(sysconfig.get_path('platlib'))
|
libpydir = abspath(sysconfig.get_path('platlib'))
|
||||||
libpyauxdir = abspath(os.path.dirname('stdlib'))
|
#libpyauxdir = abspath(os.path.dirname('stdlib'))
|
||||||
#pkg_root = join(here, name)
|
#pkg_root = join(here, name)
|
||||||
|
|
||||||
here = path.abspath(path.dirname(__file__))
|
here = path.abspath(path.dirname(__file__))
|
||||||
|
|
||||||
sys.path.insert(0, "${CMAKE_CURRENT_SOURCE_DIR}")
|
sys.path.insert(0, "${CMAKE_CURRENT_SOURCE_DIR}")
|
||||||
|
|
||||||
|
python_libdir = path.abspath(path.dirname("${PYTHON_LIBRARIES}"))
|
||||||
|
|
||||||
if platform.system() == 'Windows':
|
if platform.system() == 'Windows':
|
||||||
local_libs = []
|
local_libs = []
|
||||||
win_libs = ['wsock32','ws2_32']
|
win_libs = ['wsock32','ws2_32']
|
||||||
my_extra_link_args = ['-Wl,-export-all-symbols']
|
my_extra_link_args = ['-Wl,-export-all-symbols']
|
||||||
elif platform.system() == 'Darwin':
|
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 = []
|
win_libs = []
|
||||||
local_libs = ['Py4YAP']
|
local_libs = ['Py4YAP']
|
||||||
elif platform.system() == 'Linux':
|
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 = []
|
win_libs = []
|
||||||
local_libs = ['Py4YAP']
|
local_libs = ['Py4YAP']
|
||||||
|
|
||||||
@ -78,22 +79,21 @@ elif platform.system() == 'Linux':
|
|||||||
native_sources = ["yap4py/yap_wrap.cxx","yap4py/yapi.cpp"]
|
native_sources = ["yap4py/yap_wrap.cxx","yap4py/yapi.cpp"]
|
||||||
|
|
||||||
#gmp_dir = path.abspath(path.dirname("${GMP_LIBRARIES}"))
|
#gmp_dir = path.abspath(path.dirname("${GMP_LIBRARIES}"))
|
||||||
#python_libdir = path.abspath(path.dirname("${PYTHON_LIBRARIES}")
|
|
||||||
# Get the long description from the README file
|
# Get the long description from the README file
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
extensions = [Extension('yap4py._yap', native_sources,
|
extensions = [Extension('_yap', native_sources,
|
||||||
define_macros=[('MAJOR_VERSION', '1'),
|
define_macros=[('MAJOR_VERSION', '1'),
|
||||||
('MINOR_VERSION', '0'),
|
('MINOR_VERSION', '0'),
|
||||||
('_YAP_NOT_INSTALLED_', '1'),
|
('_YAP_NOT_INSTALLED_', '1'),
|
||||||
('YAP_PYTHON', '1'),
|
('YAP_PYTHON', '1'),
|
||||||
('_GNU_SOURCE', '1')],
|
('_GNU_SOURCE', '1')],
|
||||||
runtime_library_dirs=[abspath(sysconfig.get_path('platlib')),
|
runtime_library_dirs=[
|
||||||
abspath(sysconfig.get_path('platlib'))],
|
abspath(join(sysconfig.get_path('platlib'),'yap4py')), abspath(sysconfig.get_path('platlib')),'${CMAKE_INSTALL_FULL_LIBDIR}'],
|
||||||
swig_opts=['-modern', '-c++', '-py3',
|
swig_opts=['-modern', '-c++', '-py3',
|
||||||
'-DX_API', '-Iyap4py/include' ],
|
'-DX_API', '-Iyap4py/include' ],
|
||||||
library_dirs=[".",'../../..'],
|
library_dirs=[".",'../../..','${CMAKE_INSTALL_FULL_LIBDIR}'],
|
||||||
extra_link_args=my_extra_link_args,
|
extra_link_args=my_extra_link_args,
|
||||||
libraries=['Yap','gmp']+win_libs+local_libs,
|
libraries=['Yap','gmp']+win_libs+local_libs,
|
||||||
include_dirs=['${CMAKE_SOURCE_DIR}/H',
|
include_dirs=['${CMAKE_SOURCE_DIR}/H',
|
||||||
@ -122,7 +122,7 @@ setup_args = dict(
|
|||||||
scripts=glob(join('scripts', '*')),
|
scripts=glob(join('scripts', '*')),
|
||||||
packages=['yap4py'],
|
packages=['yap4py'],
|
||||||
ext_modules=extensions,
|
ext_modules=extensions,
|
||||||
py_modules=[],
|
sources=['yap4py/yapi.py','yap4py/yap.py','yap4py/__main__.py','yap4py/__init_.py'],
|
||||||
# package_data=package_data,
|
# package_data=package_data,
|
||||||
include_package_data=True,
|
include_package_data=True,
|
||||||
data_files = data_files,
|
data_files = data_files,
|
||||||
|
@ -16,15 +16,18 @@ if platform.system() == 'Windows':
|
|||||||
ctypes.WinDLL(dll)
|
ctypes.WinDLL(dll)
|
||||||
elif platform.system() == 'Darwin':
|
elif platform.system() == 'Darwin':
|
||||||
def load( dll ):
|
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)
|
dll = os.path.abspath(dll)
|
||||||
ctypes.CDLL(dll)
|
ctypes.CDLL(dll)
|
||||||
# load('libYap.dylib')
|
print('loaded ',dll)
|
||||||
# load('libPy4YAP.dylib')
|
|
||||||
|
# try:
|
||||||
|
# load( '_yap*.so' )
|
||||||
|
# except:
|
||||||
# load( '_yap*.dylib' )
|
# load( '_yap*.dylib' )
|
||||||
else:
|
else:
|
||||||
def load( dll ):
|
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)
|
dll = os.path.abspath(dll)
|
||||||
ctypes.CDLL(dll)
|
ctypes.CDLL(dll)
|
||||||
# \`load('_yap*.so')
|
load('_yap*.so')
|
||||||
|
@ -47,24 +47,21 @@ class Predicate( YAPPredicate ):
|
|||||||
def __init__(self, t, module=None):
|
def __init__(self, t, module=None):
|
||||||
super().__init__(t)
|
super().__init__(t)
|
||||||
|
|
||||||
class Goal(object):
|
class IQuery(YAPQuery):
|
||||||
"""Goal is a predicate instantiated under a specific environment """
|
"""Goal is a predicate instantiated under a specific environment """
|
||||||
def __init__(self, engine, g):
|
def __init__(self, engine, g):
|
||||||
self.q = engine.query(g)
|
self = engine.query(g)
|
||||||
self.e = engine
|
|
||||||
self.port = "call"
|
self.port = "call"
|
||||||
self.bindings = None
|
self.bindings = None
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
return PrologTableIter( self.e, self )
|
return PrologTableIter( self )
|
||||||
|
|
||||||
class PrologTableIter:
|
class PrologTableIter:
|
||||||
|
|
||||||
def __init__(self, e, g):
|
def __init__(self, q):
|
||||||
try:
|
try:
|
||||||
self.e = e
|
self.q = q
|
||||||
self.g = g
|
|
||||||
self.q = g.q
|
|
||||||
except:
|
except:
|
||||||
print('Error')
|
print('Error')
|
||||||
|
|
||||||
@ -77,9 +74,9 @@ class PrologTableIter:
|
|||||||
if not self.q:
|
if not self.q:
|
||||||
raise StopIteration()
|
raise StopIteration()
|
||||||
if self.q.next():
|
if self.q.next():
|
||||||
rc = self.g.bindings
|
rc = self.q.bindings
|
||||||
if self.g.port == "exit":
|
if self.q.port == "exit":
|
||||||
self.close()
|
self.q.close()
|
||||||
return rc
|
return rc
|
||||||
else:
|
else:
|
||||||
if self.q:
|
if self.q:
|
||||||
@ -179,7 +176,7 @@ class YAPShell:
|
|||||||
bindings = []
|
bindings = []
|
||||||
g = python_query(self, query)
|
g = python_query(self, query)
|
||||||
if not self.q:
|
if not self.q:
|
||||||
self.it = Goal( engine, g )
|
self.it = IQuery( engine, g )
|
||||||
for bind in self.it:
|
for bind in self.it:
|
||||||
bindings += [bind]
|
bindings += [bind]
|
||||||
if do_ask:
|
if do_ask:
|
||||||
|
@ -64,6 +64,8 @@ yap_ipython/frontend.py
|
|||||||
yap_ipython/parallel.py
|
yap_ipython/parallel.py
|
||||||
yap_ipython/html.py
|
yap_ipython/html.py
|
||||||
yap_ipython/__main__.py
|
yap_ipython/__main__.py
|
||||||
|
_version.py
|
||||||
|
yap_ipython/_version.py
|
||||||
yap_ipython/testing/iptest.py
|
yap_ipython/testing/iptest.py
|
||||||
yap_ipython/testing/skipdoctest.py
|
yap_ipython/testing/skipdoctest.py
|
||||||
yap_ipython/testing/tools.py
|
yap_ipython/testing/tools.py
|
||||||
@ -421,13 +423,14 @@ add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-
|
|||||||
|
|
||||||
add_custom_target(YAP_KERNEL ALL
|
add_custom_target(YAP_KERNEL ALL
|
||||||
COMMAND ${CMAKE_COMMAND} -E tar xzf yap.tgz
|
COMMAND ${CMAKE_COMMAND} -E tar xzf yap.tgz
|
||||||
COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} build sdist bdist
|
|
||||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
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
|
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
|
COMMAND ${PYTHON_EXECUTABLE} -m yap_kernel.kernelspec
|
||||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})")
|
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})")
|
||||||
|
|
||||||
|
@ -40,14 +40,15 @@ here = os.path.abspath(os.path.dirname(__file__))
|
|||||||
packages = ['yap_kernel','yap_ipython']
|
packages = ['yap_kernel','yap_ipython']
|
||||||
# pkg_root = pjoin(here, name)
|
# pkg_root = pjoin(here, name)
|
||||||
|
|
||||||
# for d, _, _ in os.walk(pjoin(here, 'yap_kernel')):
|
for d, _, _ in os.walk(pjoin(here, 'yap_kernel')):
|
||||||
# if os.path.exists(pjoin(d, '__init__.py')):
|
if os.path.exists(pjoin(d, '__init__.py')):
|
||||||
# packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
|
packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
|
||||||
# for d, _, _ in os.walk(pjoin(here, 'yap_ipython')):
|
for d, _, _ in os.walk(pjoin(here, 'yap_ipython')):
|
||||||
# if os.path.exists(pjoin(d, '__init__.py')):
|
if os.path.exists(pjoin(d, '__init__.py')):
|
||||||
# packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
|
packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
|
||||||
|
|
||||||
sys.path.insert(0, here)
|
sys.path.insert(0, here)
|
||||||
|
sys.path.insert(0, pjoin(here,'..','swig'))
|
||||||
package_data = {
|
package_data = {
|
||||||
'yap_ipython': ['prolog/*.*'],
|
'yap_ipython': ['prolog/*.*'],
|
||||||
'yap_kernel': ['resources/*.*']
|
'yap_kernel': ['resources/*.*']
|
||||||
|
@ -219,9 +219,9 @@ class ExecutionResult(object):
|
|||||||
|
|
||||||
def raise_error(self):
|
def raise_error(self):
|
||||||
"""Reraises error if `success` is `False`, otherwise does nothing"""
|
"""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
|
raise self.error_before_exec
|
||||||
if self.error_in_exec is not None:
|
if self.error_in_exec:
|
||||||
raise self.error_in_exec
|
raise self.error_in_exec
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
@ -2661,6 +2661,9 @@ class InteractiveShell(SingletonConfigurable):
|
|||||||
-------
|
-------
|
||||||
result : :class:`ExecutionResult`
|
result : :class:`ExecutionResult`
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
print("go")
|
||||||
|
result = None
|
||||||
try:
|
try:
|
||||||
result = self._yrun_cell(
|
result = self._yrun_cell(
|
||||||
raw_cell, store_history, silent, shell_futures)
|
raw_cell, store_history, silent, shell_futures)
|
||||||
@ -2668,6 +2671,7 @@ class InteractiveShell(SingletonConfigurable):
|
|||||||
self.events.trigger('post_execute')
|
self.events.trigger('post_execute')
|
||||||
if not silent:
|
if not silent:
|
||||||
self.events.trigger('post_run_cell', result)
|
self.events.trigger('post_run_cell', result)
|
||||||
|
print("go", result)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def _run_cell(self, raw_cell, store_history, silent, shell_futures):
|
def _run_cell(self, raw_cell, store_history, silent, shell_futures):
|
||||||
|
@ -11,15 +11,15 @@
|
|||||||
* -
|
* -
|
||||||
*/
|
*/
|
||||||
|
|
||||||
%% :- module( jupyter,
|
% :- module( jupyter,
|
||||||
%% [jupyter_query/3,
|
% [jupyter_query/3,
|
||||||
%% errors/2,
|
% errors/2,
|
||||||
%% ready/2,
|
% ready/2,
|
||||||
%% completion/2,
|
% completion/2,
|
||||||
|
|
||||||
%% ]
|
% ]
|
||||||
%% ).
|
%% ).
|
||||||
|
:- [library(hacks)].
|
||||||
|
|
||||||
:- reexport(library(yapi)).
|
:- reexport(library(yapi)).
|
||||||
:- use_module(library(lists)).
|
:- use_module(library(lists)).
|
||||||
@ -32,26 +32,24 @@ jupyter_query(Caller, Cell, Line ) :-
|
|||||||
jupyter_cell(Caller, Cell, Line).
|
jupyter_cell(Caller, Cell, Line).
|
||||||
|
|
||||||
jupyter_cell(_Caller, Cell, _) :-
|
jupyter_cell(_Caller, Cell, _) :-
|
||||||
jupyter_consult(Cell),
|
jupyter_consult(Cell), %stack_dump,
|
||||||
fail.
|
fail.
|
||||||
jupyter_cell( _Caller, _, Line ) :-
|
jupyter_cell( _Caller, _, Line ) :-
|
||||||
blank( Line ),
|
blank( Line ),
|
||||||
!.
|
!.
|
||||||
jupyter_cell( _Caller, _, [] ) :- !.
|
jupyter_cell( _Caller, _, [] ) :- !.
|
||||||
jupyter_cell( Caller, _, Line ) :-
|
jupyter_cell( Caller, _, Line ) :-
|
||||||
gated_call(
|
Self := Caller.query,
|
||||||
enter_cell(call),
|
python_query( Self, Line ).
|
||||||
python_query( Caller, Line ),
|
|
||||||
Port,
|
|
||||||
enter_cell(Port)
|
|
||||||
).
|
|
||||||
|
|
||||||
jupyter_consult(Text) :-
|
jupyter_consult(Text) :-
|
||||||
blank( Text ),
|
blank( Text ),
|
||||||
!.
|
!.
|
||||||
jupyter_consult(Cell) :-
|
jupyter_consult(Cell) :-
|
||||||
open_mem_read_stream( Cell, Stream),
|
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?
|
%should load_files close?
|
||||||
|
|
||||||
blank(Text) :-
|
blank(Text) :-
|
||||||
@ -62,29 +60,16 @@ blankc(' ').
|
|||||||
blankc('\n').
|
blankc('\n').
|
||||||
blankc('\t').
|
blankc('\t').
|
||||||
|
|
||||||
enter_cell(retry) :-
|
|
||||||
enter_cell(call).
|
streams(false) :-
|
||||||
enter_cell(call) :-
|
% close( user_input),
|
||||||
into_cell.
|
close( user_error ),
|
||||||
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 ).
|
close( user_output ).
|
||||||
|
streams(true) :-
|
||||||
|
% open('/python/input', read, _Input, [alias(user_input),bom(false)]),
|
||||||
into_cell :-
|
open('/python/sys.stdout', append, _Output, [alias(user_output)]),
|
||||||
nb_setval(jupyter_cell, on),
|
open('/python/sys.stderr', append, _Error, [alias(user_error)]),
|
||||||
open('/python/sys.input', read, _Input, [bom(false)]),
|
% set_prolog_flag(user_input,_Input),
|
||||||
open('/python/sys.stdout', append, _Output, []),
|
|
||||||
open('/python/sys.stderr', append, _Error, []),
|
|
||||||
set_prolog_flag(user_input,_Output),
|
|
||||||
set_prolog_flag(user_output,_Output),
|
set_prolog_flag(user_output,_Output),
|
||||||
set_prolog_flag(user_error,_Error).
|
set_prolog_flag(user_error,_Error).
|
||||||
|
|
||||||
@ -185,7 +170,7 @@ predicate(N,P,A) :-
|
|||||||
cont(0, F, P, P0) :-
|
cont(0, F, P, P0) :-
|
||||||
atom_concat( F, P, P0 ).
|
atom_concat( F, P, P0 ).
|
||||||
cont( _, F, P, PB ):-
|
cont( _, F, P, PB ):-
|
||||||
atom_concat( [F, P, '('], PB ).
|
atom_concat( [F, P, '( )'], PB ).
|
||||||
|
|
||||||
|
|
||||||
ready(_Self, Line ) :-
|
ready(_Self, Line ) :-
|
||||||
|
@ -3,15 +3,14 @@ import sys
|
|||||||
import abc
|
import abc
|
||||||
import math
|
import math
|
||||||
import itertools
|
import itertools
|
||||||
|
import trace
|
||||||
|
|
||||||
|
|
||||||
from typing import Iterator, List, Tuple, Iterable, Union
|
from typing import Iterator, List, Tuple, Iterable, Union
|
||||||
from traitlets import Bool, Enum, observe, Int
|
from traitlets import Bool, Enum, observe, Int
|
||||||
|
|
||||||
try:
|
|
||||||
from yap4py.yapi import Engine, Goal, EngineArgs, PrologTableIter
|
from yap4py.yapi import *
|
||||||
except:
|
|
||||||
print("Could not load _yap dll.")
|
|
||||||
from yap_ipython.core.completer import Completer, Completion
|
from yap_ipython.core.completer import Completer, Completion
|
||||||
from yap_ipython.utils.strdispatch import StrDispatch
|
from yap_ipython.utils.strdispatch import StrDispatch
|
||||||
# import yap_ipython.core
|
# import yap_ipython.core
|
||||||
@ -38,6 +37,7 @@ enter_cell = namedtuple('enter_cell', 'self' )
|
|||||||
exit_cell = namedtuple('exit_cell', 'self' )
|
exit_cell = namedtuple('exit_cell', 'self' )
|
||||||
completions = namedtuple('completions', 'txt self' )
|
completions = namedtuple('completions', 'txt self' )
|
||||||
errors = namedtuple('errors', 'self text' )
|
errors = namedtuple('errors', 'self text' )
|
||||||
|
streams = namedtuple('streams', ' text' )
|
||||||
|
|
||||||
|
|
||||||
class YAPInputSplitter(InputSplitter):
|
class YAPInputSplitter(InputSplitter):
|
||||||
@ -100,6 +100,7 @@ class YAPInputSplitter(InputSplitter):
|
|||||||
Python line."""
|
Python line."""
|
||||||
t = self.physical_line_transforms + \
|
t = self.physical_line_transforms + \
|
||||||
[self.assemble_logical_lines] + self.logical_line_transforms
|
[self.assemble_logical_lines] + self.logical_line_transforms
|
||||||
|
return t
|
||||||
|
|
||||||
def engine(self, engine):
|
def engine(self, engine):
|
||||||
self.yapeng = engine
|
self.yapeng = engine
|
||||||
@ -107,11 +108,11 @@ 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
|
||||||
"""
|
"""
|
||||||
|
if text == self.shell.os:
|
||||||
|
return True
|
||||||
if not line:
|
if not line:
|
||||||
(_,line,_) = self.shell.prolog_cell(text)
|
line = text.rstrip()
|
||||||
line = line.strip().rstrip()
|
(line, _, _, _)=self.shell.clean_end(line)
|
||||||
if not line:
|
|
||||||
return False
|
|
||||||
self.errors = []
|
self.errors = []
|
||||||
self.yapeng.mgoal(errors(self, line),"user")
|
self.yapeng.mgoal(errors(self, line),"user")
|
||||||
return self.errors != []
|
return self.errors != []
|
||||||
@ -496,9 +497,11 @@ class YAPCompleter(Completer):
|
|||||||
"""
|
"""
|
||||||
self.matches = []
|
self.matches = []
|
||||||
prolog_res = self.shell.yapeng.mgoal(completions(text, self), "user")
|
prolog_res = self.shell.yapeng.mgoal(completions(text, self), "user")
|
||||||
|
if self.matches:
|
||||||
|
return text, self.matches
|
||||||
magic_res = self.magic_matches(text)
|
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.shell = shell
|
||||||
self.yapeng = Engine()
|
self.yapeng = Engine()
|
||||||
self.yapeng.goal(use_module(library("jupyter")))
|
self.yapeng.goal(use_module(library("jupyter")))
|
||||||
self.q = None
|
self.query = None
|
||||||
self.port = "call"
|
|
||||||
self.os = None
|
self.os = None
|
||||||
self.it = None
|
self.it = None
|
||||||
self.shell.yapeng = self.yapeng
|
self.shell.yapeng = self.yapeng
|
||||||
@ -521,41 +523,58 @@ class YAPRun:
|
|||||||
"""
|
"""
|
||||||
if not text:
|
if not text:
|
||||||
return []
|
return []
|
||||||
|
if text == self.os:
|
||||||
|
return self.errors
|
||||||
self.errors=[]
|
self.errors=[]
|
||||||
|
(text,_,_,_) = self.clean_end(text)
|
||||||
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):
|
||||||
#
|
#
|
||||||
# construct a self.query from a one-line string
|
# construct a self.queryuery from a one-line string
|
||||||
# self.q is opaque to Python
|
# self.query is opaque to Python
|
||||||
program,query,mx = self.prolog_cell(s)
|
try:
|
||||||
Found = False
|
program,query,stop,howmany = self.prolog_cell(s)
|
||||||
|
found = False
|
||||||
if query != self.os:
|
if s != 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
|
self.os = s
|
||||||
for answ in self.it:
|
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
|
found = True
|
||||||
self.bindings += [answ]
|
self.bindings += [answer]
|
||||||
self.iterations += 1
|
self.iterations += 1
|
||||||
if mx == self.iterations:
|
if stop and howmany == self.iterations:
|
||||||
return True, self.bindings
|
self.query.close()
|
||||||
port = self.it.port
|
self.query = None
|
||||||
if port == "exit":
|
|
||||||
self.q = None
|
|
||||||
self.os = None
|
self.os = None
|
||||||
return True, self.bindings
|
return True, self.bindings
|
||||||
if port == "fail":
|
if self.query.port == "exit":
|
||||||
self.q = none
|
self.query.close()
|
||||||
|
self.query = None
|
||||||
self.os = None
|
self.os = None
|
||||||
if self.bindings_message:
|
sys.stderr.writeln('Done, with', self.bindings)
|
||||||
return True,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,
|
def _yrun_cell(self, raw_cell, store_history=True, silent=False,
|
||||||
@ -573,7 +592,7 @@ class YAPRun:
|
|||||||
IPython's machinery, this
|
IPython's machinery, this
|
||||||
should be set to False.
|
should be set to False.
|
||||||
silent : bool
|
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.
|
and logging. silent=True forces store_history=False.
|
||||||
shell_futures : bool
|
shell_futures : bool
|
||||||
If True, the code will share future statements with the interactive
|
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
|
has_raised = False
|
||||||
try:
|
try:
|
||||||
state = None
|
state = None
|
||||||
self.shell.bindings = dict = {}
|
self.bindings = dicts = []
|
||||||
if cell.strip():
|
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 )
|
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:
|
if state:
|
||||||
self.shell.last_execution_succeeded = True
|
self.shell.last_execution_succeeded = True
|
||||||
self.result.result = (True, dict)
|
self.result.result = (True, dicts)
|
||||||
else:
|
else:
|
||||||
self.shell.last_execution_succeeded = True
|
self.shell.last_execution_succeeded = True
|
||||||
self.result.result = (True, {})
|
self.result.result = (True, {})
|
||||||
@ -735,50 +773,49 @@ v If True, avoid side-effects, such as implicit displayhooks and
|
|||||||
|
|
||||||
return self.result
|
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):
|
def prolog_cell(self,s):
|
||||||
"""
|
"""
|
||||||
Trasform a text into program+query. A query is the
|
Trasform a text into program+query. A query is the
|
||||||
last line if the last line is non-empty and does not terminate
|
last line if the last line is non-empty and does not terminate
|
||||||
on a dot. You can also finish with
|
on a dot. You can also finish with
|
||||||
|
|
||||||
- `*`: you request all solutions
|
- `;`: you request all solutions
|
||||||
- '^': you want to check if there is an answer
|
- ';'[N]: you want an answer; optionally you want N answers
|
||||||
- '?'[N]: you want an answer; optionally you want N answers
|
|
||||||
|
|
||||||
If the line terminates on a `*/` or starts on a `%` we assume the line
|
If the line terminates on a `*/` or starts on a `%` we assume the line
|
||||||
is a comment.
|
is a comment.
|
||||||
"""
|
"""
|
||||||
s = s.rstrip()
|
s0 = s.rstrip(' \n\t\i')
|
||||||
take = 0
|
[program,x,query] = s0.rpartition('\n')
|
||||||
its = 0
|
if query[-1] == '.':
|
||||||
s0 = ''
|
return s,'',False,0
|
||||||
for c in s:
|
(query, _,loop, sols) = self.clean_end(query)
|
||||||
if c == '\n' or c.isspace():
|
return (program, query, loop, sols)
|
||||||
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
|
|
||||||
|
@ -428,12 +428,18 @@ load_files(Files,Opts) :-
|
|||||||
'$lf'(Fs, Mod, Call, TOpts), fail;
|
'$lf'(Fs, Mod, Call, TOpts), fail;
|
||||||
true
|
true
|
||||||
).
|
).
|
||||||
'$lf'(user, Mod, _, TOpts) :- !,
|
'$lf'(user, Mod, Call, TOpts) :-
|
||||||
b_setval('$user_source_file', user),
|
!,
|
||||||
'$do_lf'(Mod, user_input, user_input, user_input, TOpts).
|
stream_property( S, alias( user_input )),
|
||||||
'$lf'(user_input, Mod, _, TOpts) :- !,
|
'$set_lf_opt'('$from_stream', TOpts, true),
|
||||||
b_setval('$user_source_file', user_input),
|
'$set_lf_opt'( stream , TOpts, S),
|
||||||
'$do_lf'(Mod, user_input, user_input, user_input, TOpts).
|
'$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'(File, Mod, Call, TOpts) :-
|
||||||
'$lf_opt'(stream, TOpts, Stream),
|
'$lf_opt'(stream, TOpts, Stream),
|
||||||
b_setval('$user_source_file', File),
|
b_setval('$user_source_file', File),
|
||||||
@ -453,7 +459,7 @@ load_files(Files,Opts) :-
|
|||||||
'$start_lf'(If, Mod, Stream, TOpts, File, Y, Reexport, Imports),
|
'$start_lf'(If, Mod, Stream, TOpts, File, Y, Reexport, Imports),
|
||||||
close(Stream).
|
close(Stream).
|
||||||
|
|
||||||
% consulting from a stre
|
% consulting from a stream
|
||||||
'$start_lf'(_not_loaded, Mod, Stream, TOpts, UserFile, File, _Reexport, _Imports) :-
|
'$start_lf'(_not_loaded, Mod, Stream, TOpts, UserFile, File, _Reexport, _Imports) :-
|
||||||
'$lf_opt'('$from_stream', TOpts, true ),
|
'$lf_opt'('$from_stream', TOpts, true ),
|
||||||
!,
|
!,
|
||||||
@ -650,7 +656,7 @@ db_files(Fs) :-
|
|||||||
'$load_files'(Fs, [consult(db), if(not_loaded)], exo_files(Fs)).
|
'$load_files'(Fs, [consult(db), if(not_loaded)], exo_files(Fs)).
|
||||||
|
|
||||||
|
|
||||||
'$csult'(Fs, M) :-
|
'$csult'(Fs, _M) :-
|
||||||
'$skip_list'(_, Fs ,L),
|
'$skip_list'(_, Fs ,L),
|
||||||
L \== [],
|
L \== [],
|
||||||
user:dot_qualified_goal(Fs),
|
user:dot_qualified_goal(Fs),
|
||||||
@ -1632,7 +1638,7 @@ End of conditional compilation.
|
|||||||
|
|
||||||
consult_depth(LV) :- '$show_consult_level'(LV).
|
consult_depth(LV) :- '$show_consult_level'(LV).
|
||||||
|
|
||||||
:- '$add_multifile'(Name,Arity,Module).
|
:- '$add_multifile'(dot_qualified_goal,2,user).
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@}
|
@}
|
||||||
|
Reference in New Issue
Block a user