This commit is contained in:
Vitor Santos Costa 2016-04-12 16:22:53 +01:00
parent c0c002134b
commit 786cfb71ad
15 changed files with 267 additions and 162 deletions

View File

@ -123,7 +123,15 @@ endif()
include(java) include(java)
if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") set(WITH_PYTHON YES CACHE FILEPATH "Try to use Python (currently Python 3)")
if (WITH_PYTHON)
include(python)
endif()
if (
)
cmake_policy( SET CMP0042 NEW) cmake_policy( SET CMP0042 NEW)
#cmake_policy( NO_POLICY_SCOPE ) #cmake_policy( NO_POLICY_SCOPE )
endif() endif()

View File

@ -9,13 +9,13 @@ extern "C" {
#include "blobs.h" #include "blobs.h"
X_API char *Yap_TermToString(Term t, char *s, size_t sz, size_t *length, X_API char *Yap_TermToString(Term t, char *s, size_t sz, size_t *length,
encoding_t *encodingp, int flags); encoding_t *encodingp, int flags);
X_API void YAP_UserCPredicate(const char *, YAP_UserCPred, YAP_Arity arity); X_API void YAP_UserCPredicate(const char *, YAP_UserCPred, YAP_Arity arity);
X_API void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, YAP_Arity, X_API void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, YAP_Arity,
YAP_Term); YAP_Term);
X_API void YAP_UserBackCPredicate(const char *, YAP_UserCPred, YAP_UserCPred, X_API void YAP_UserBackCPredicate(const char *, YAP_UserCPred, YAP_UserCPred,
YAP_Arity, YAP_Arity); YAP_Arity, YAP_Arity);
} }
YAPAtomTerm::YAPAtomTerm(char *s) { // build string YAPAtomTerm::YAPAtomTerm(char *s) { // build string
@ -445,8 +445,6 @@ YAPQuery::YAPQuery(YAPPredicate p, YAPTerm ts[]) : YAPPredicate(p.ap) {
YAPListTerm YAPQuery::namedVars() { YAPListTerm YAPQuery::namedVars() {
CACHE_REGS CACHE_REGS
Term o = vnames.term(); Term o = vnames.term();
Yap_DebugPlWrite(o);
printf("<<<<<<<<<<<<<<<<-------------------------\n");
return o; // should be o return o; // should be o
} }
@ -454,9 +452,6 @@ bool YAPQuery::next() {
CACHE_REGS CACHE_REGS
int result; int result;
Yap_DebugPlWrite(vnames.term());
fprintf(stderr, "++++++++++++++\n");
BACKUP_MACHINE_REGS(); BACKUP_MACHINE_REGS();
if (q_open != 1) if (q_open != 1)
return false; return false;
@ -464,17 +459,15 @@ bool YAPQuery::next() {
return false; return false;
// don't forget, on success these guys must create slots // don't forget, on success these guys must create slots
if (this->q_state == 0) { if (this->q_state == 0) {
fprintf(stderr, "+++++ ap=%p +++++++++\n", ap);
Yap_DebugPlWrite(Yap_GetFromSlot(q_g));
fprintf(stderr, "+++++ ap +++++++++\n");
result = (bool)YAP_EnterGoal((YAP_PredEntryPtr)ap, q_g, &q_h); result = (bool)YAP_EnterGoal((YAP_PredEntryPtr)ap, q_g, &q_h);
Yap_DebugPlWrite(Yap_GetFromSlot(q_g));
fprintf(stderr, "+++++ ap=%d +++++++++\n", result);
} else { } else {
LOCAL_AllowRestart = q_open; LOCAL_AllowRestart = q_open;
result = (bool)YAP_RetryGoal(&q_h); result = (bool)YAP_RetryGoal(&q_h);
} }
q_state = 1; q_state = 1;
if (Yap_GetException()) {
throw(YAPError(SYSTEM_ERROR_INTERNAL));
}
if (!result) { if (!result) {
YAP_LeaveGoal(FALSE, &q_h); YAP_LeaveGoal(FALSE, &q_h);
q_open = 0; q_open = 0;
@ -495,6 +488,17 @@ void YAPQuery::cut() {
RECOVER_MACHINE_REGS(); RECOVER_MACHINE_REGS();
} }
bool YAPQuery::deterministic() {
CACHE_REGS
BACKUP_MACHINE_REGS();
if (q_open != 1 || q_state == 0)
return false;
choiceptr myB = (choiceptr)(LCL0 - q_h.b);
return (B >= myB);
RECOVER_MACHINE_REGS();
}
void YAPQuery::close() { void YAPQuery::close() {
CACHE_REGS CACHE_REGS
@ -595,12 +599,7 @@ YAPEngine::YAPEngine(char *savedState, size_t stackSize, size_t trailSize,
init_args.YapPrologBootFile = bootFile; init_args.YapPrologBootFile = bootFile;
init_args.YapPrologGoal = goal; init_args.YapPrologGoal = goal;
init_args.YapPrologTopLevelGoal = topLevel; init_args.YapPrologTopLevelGoal = topLevel;
init_args.HaltAfter init_args.HaltAfterConsult = script;
= script;
init_args.FastBoot = fastBoot; init_args.FastBoot = fastBoot;
yerror = YAPError(); yerror = YAPError();
delYAPCallback(); delYAPCallback();

View File

@ -1,7 +1,7 @@
#define YAP_CPP_INTERFACE 1 #define YAP_CPP_INTERFACE 1
#include <gmpxx.h>
//! @{ //! @{
@ -23,9 +23,7 @@
#include <string> #include <string>
// Bad export from Python // Bad export from Python
#ifdef HAVE_STAT
#undef HAVE_STAT
#endif
#include <config.h> #include <config.h>
extern "C" { extern "C" {

View File

@ -43,7 +43,7 @@ public:
inline YAPQuery(const char *s): YAPPredicate(s, t, names) inline YAPQuery(const char *s): YAPPredicate(s, t, names)
{ {
vnames = YAPListTerm( names ); vnames = YAPListTerm( names );
initQuery( t ); initQuery( t );
}; };
@ -58,6 +58,9 @@ public:
/// ask for the next solution of the current query /// ask for the next solution of the current query
/// same call for every solution /// same call for every solution
bool next(); bool next();
/// does this query have open choice-points?
/// or is it deterministic?
bool deterministic();
/// represent the top-goal /// represent the top-goal
const char *text(); const char *text();
/// remove alternatives in the current search space, and finish the current query /// remove alternatives in the current search space, and finish the current query

View File

@ -1,9 +1,13 @@
#ifndef __unix__
#define X_API
#endif
#ifndef YAPT_HH #ifndef YAPT_HH
#define YAPT_HH 1 #define YAPT_HH 1
class YAPAtomTerm; class YAPAtomTerm;
extern "C" Term X_API YAP_ReadBuffer(const char *s, Term *tp); extern "C" X_API Term YAP_ReadBuffer(const char *s, Term *tp);
/** /**
* @brief Generic Prolog Term * @brief Generic Prolog Term

View File

@ -337,9 +337,7 @@ INLINE_ONLY inline EXTERN int IsStringTerm(Term t) {
#include <stdio.h> #include <stdio.h>
#if defined(__cplusplus) #if !defined(__cplusplus)
#include <gmpxx.h>
#elif !defined(__GMP_H__)
#include <gmp.h> #include <gmp.h>
#endif #endif

View File

@ -47,9 +47,6 @@
#endif /* THREADS && (YAPOR_COW || YAPOR_SBA || YAPOR_COPY) */ #endif /* THREADS && (YAPOR_COW || YAPOR_SBA || YAPOR_COPY) */
// Bad export from Python // Bad export from Python
#ifdef HAVE_STAT
#undef HAVE_STAT
#endif
#include "config.h" #include "config.h"
#ifndef COROUTINING #ifndef COROUTINING

26
cmake/python.cmake Normal file
View File

@ -0,0 +1,26 @@
#BREW install for Python3
if (APPLE)
foreach (i 3.6 3.5 3.4 3.3 3.2 3.1 3.0)
set (PYTHON_INCLUDE_DIRS /usr/local/Frameworks/Python.framework/Versions/${i}/Headers)
message("Trying Python ${i}")
if (EXISTS ${PYTHON_INCLUDE_DIRS})
set (PYTHON_EXECUTABLE /usr/local/bin/python${i} CACHE FILEPATH "Path to a program" FORCE )
set (PYTHON_INCLUDE_DIR /usr/local/Frameworks/Python.framework/Versions/${i}/include/python${i}m
CACHE PATH "Path to a file." FORCE )
set (PYTHON_LIBRARY /usr/local/Frameworks/Python.framework/Versions/${i}/lib/libpython${i}.dylib
CACHE FILEPATH "Path to a library" FORCE )
break()
endif()
endforeach()
endif()
find_package(PythonInterp)
find_package(PythonLibs)
macro_log_feature (PYTHONLIBS_FOUND "Python"
"Use Python System"
"http://www.python.org" FALSE)

View File

@ -146,6 +146,7 @@ int main(int argc, char **argv)
YAP_RunGoalOnce(t_goal); YAP_RunGoalOnce(t_goal);
} }
} }
YAP_Reset(YAP_FULL_RESET); YAP_Reset(YAP_FULL_RESET);
/* End preprocessor code */ /* End preprocessor code */

View File

@ -240,9 +240,9 @@ typedef struct yap_boot_params {
/* if NON-NULL, a path to extend file-search-path */ /* if NON-NULL, a path to extend file-search-path */
char *YapPrologAddPath; char *YapPrologAddPath;
/* if previous NON-NULL and TRUE, halt after consulting that file */ /* if previous NON-NULL and TRUE, halt after consulting that file */
int HaltAfterConsult; bool HaltAfterConsult;
/* ignore .yaprc, .prolog.ini, etc. files. */ /* ignore .yaprc, .prolog.ini, etc. files. */
int FastBoot; bool FastBoot;
/* the next field only interest YAPTAB */ /* the next field only interest YAPTAB */
/* if NON-0, maximum size for Table Space */ /* if NON-0, maximum size for Table Space */
unsigned long int MaxTableSpaceSize; unsigned long int MaxTableSpaceSize;

View File

@ -31,15 +31,15 @@ ENDIF(MSVC)
set_source_files_properties(${outfile} PROPERTIES GENERATED TRUE) set_source_files_properties(${outfile} PROPERTIES GENERATED TRUE)
endfunction() endfunction()
Add_custom_target (plmyddas ALL DEPENDS ${MYDDAS_YPP} ) # WORKING_DIRECTORY ${CMAKE_BINARY_DIR} )
foreach(file ${MYDDAS_YPP}) foreach(file ${MYDDAS_YPP})
cpp_compile( MYDDAS_YAP ${file}) cpp_compile( MYDDAS_YAP ${file})
#message("outfiles=${MYDDAS_YAP}\n") #message("outfiles=${MYDDAS_YAP}\n")
endforeach() endforeach()
Add_custom_target (plmyddas ALL DEPENDS ${MYDDAS_YPP} ${MYDDAS_YAP} ) # WORKING_DIRECTORY ${CMAKE_BINARY_DIR} )
install(FILES ${MYDDAS_YAP} install(FILES ${MYDDAS_YAP}
DESTINATION ${libpl} DESTINATION ${libpl}
) )

View File

@ -10,11 +10,6 @@ set (PYTHON_SOURCES
#set( PYTHON_LIBRARY /usr/local/opt/python/Frameworks/Python.framework/Versions/Current/lib/libpython2.7.dylib) # - path to the python library #set( PYTHON_LIBRARY /usr/local/opt/python/Frameworks/Python.framework/Versions/Current/lib/libpython2.7.dylib) # - path to the python library
#set( PYTHON_INCLUDE_DIR /usr/local/opt/python/Frameworks/Python.framework/Versions/Current/include/python2.7 ) # - path to where Python.h is found #set( PYTHON_INCLUDE_DIR /usr/local/opt/python/Frameworks/Python.framework/Versions/Current/include/python2.7 ) # - path to where Python.h is found
macro_optional_find_package(PythonInterp ON)
macro_optional_find_package (PythonLibs ON)
macro_log_feature (PYTHONLIBS_FOUND "Python"
"Use Python System"
"http://www.python.org" FALSE)
if (PYTHONLIBS_FOUND) # PYTHONLIBS_FOUND - have the Python libs been found if (PYTHONLIBS_FOUND) # PYTHONLIBS_FOUND - have the Python libs been found
# PYTHON_LIBRARIES - path to the python library # PYTHON_LIBRARIES - path to the python library
@ -45,7 +40,7 @@ if (PYTHONLIBS_FOUND) # PYTHONLIBS_FOUND - have the Python l
add_library (libpython SHARED ${PYTHON_SOURCES}) add_library (libpython SHARED ${PYTHON_SOURCES})
target_link_libraries(libpython libYap ${PYTHON_LIBRARIES}) target_link_libraries(libpython libYap ${PYTHON_LIBRARIES})
set_target_properties (libpython PROPERTIES PREFIX "") set_target_properties (libpython PROPERTIES PREFIX "")

View File

@ -136,7 +136,7 @@ static int copy_to_dictionary(PyObject *dict, term_t targ, term_t taux) {
if (lhs == NULL) { if (lhs == NULL) {
return FALSE; return FALSE;
} }
if (!PL_get_arg(2, targ, tright)) { if (!PL_get_arg(2, targ, tright)) {
return FALSE; return FALSE;
} }
rhs = term_to_python(tright); rhs = term_to_python(tright);
@ -438,8 +438,8 @@ static PyObject *bip_sum(term_t t) {
return NULL; return NULL;
} }
Py_INCREF(result); Py_INCREF(result);
}
#endif #endif
}
#ifndef SLOW_SUM #ifndef SLOW_SUM
/* Fast addition by keeping temporary sums in C instead of new Python objects. /* Fast addition by keeping temporary sums in C instead of new Python objects.
@ -521,14 +521,17 @@ to the more general routine.
if (PyInt_CheckExact(item)) { if (PyInt_CheckExact(item)) {
PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
f_result += (double)PyInt_AS_LONG(item); f_result += (double)PyInt_AS_LONG(item);
PyFPE_END_PROTECT(f_result) Py_DECREF(item);
continue;
}
#else #else
if (PyLong_CheckExact(item)) { if (PyLong_CheckExact(item)) {
PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
f_result += PyLong_AsDouble(item); f_result += PyLong_AsDouble(item);
#endif
PyFPE_END_PROTECT(f_result) Py_DECREF(item); PyFPE_END_PROTECT(f_result) Py_DECREF(item);
continue; continue;
} }
#endif
result = PyFloat_FromDouble(f_result); result = PyFloat_FromDouble(f_result);
temp = PyNumber_Add(result, item); temp = PyNumber_Add(result, item);
Py_DECREF(result); Py_DECREF(result);
@ -539,8 +542,8 @@ to the more general routine.
return NULL; return NULL;
} }
} }
}
#endif #endif
}
for (;;) { for (;;) {
item = PyIter_Next(iter); item = PyIter_Next(iter);
@ -667,7 +670,7 @@ static PyObject *bip_range(term_t t) {
#if PY_MAJOR_VERSION < 3 #if PY_MAJOR_VERSION < 3
PyObject *w = PyInt_FromLong(ilow); PyObject *w = PyInt_FromLong(ilow);
#else #else
PyObject *w = PyLong_FromLong(ilow); PyObject *w = PyLong_FromLong(ilow);
#endif #endif
if (w == NULL) { if (w == NULL) {
Py_DECREF(v); Py_DECREF(v);
@ -762,7 +765,7 @@ static PyObject *term_to_python(term_t t) {
#if PY_MAJOR_VERSION < 3 #if PY_MAJOR_VERSION < 3
return PyInt_FromLong(j); return PyInt_FromLong(j);
#else #else
return PyLong_FromLong(j); return PyLong_FromLong(j);
#endif #endif
} }
case PL_FLOAT: { case PL_FLOAT: {
@ -996,7 +999,7 @@ static PyObject *term_to_python(term_t t) {
#if PY_MAJOR_VERSION < 3 #if PY_MAJOR_VERSION < 3
return PyNumber_Divide(lhs, rhs); return PyNumber_Divide(lhs, rhs);
#else #else
return PyNumber_TrueDivide(lhs, rhs); return PyNumber_TrueDivide(lhs, rhs);
#endif #endif
} else if (fun == FUNCTOR_sqbrackets2) { } else if (fun == FUNCTOR_sqbrackets2) {
// //
@ -1360,9 +1363,9 @@ static foreign_t python_to_term(PyObject *pVal, term_t t) {
wchar_t *ptr = malloc(sizeof(wchar_t) * sz); wchar_t *ptr = malloc(sizeof(wchar_t) * sz);
sz = PyUnicode_AsWideChar((PyUnicodeObject *)pVal, ptr, sz - 1); sz = PyUnicode_AsWideChar((PyUnicodeObject *)pVal, ptr, sz - 1);
#else #else
Py_ssize_t sz = PyUnicode_GetLength(pVal) + 1; Py_ssize_t sz = PyUnicode_GetLength(pVal) + 1;
wchar_t *ptr = malloc(sizeof(wchar_t) * sz); wchar_t *ptr = malloc(sizeof(wchar_t) * sz);
sz = PyUnicode_AsWideChar(pVal, ptr, sz); sz = PyUnicode_AsWideChar(pVal, ptr, sz);
#endif #endif
tmp_atom = PL_new_atom_wchars(sz, ptr); tmp_atom = PL_new_atom_wchars(sz, ptr);
free(ptr); free(ptr);
@ -1430,24 +1433,22 @@ static foreign_t python_to_term(PyObject *pVal, term_t t) {
PL_cons_functor(to, FUNCTOR_curly1, to); PL_cons_functor(to, FUNCTOR_curly1, to);
return PL_unify(t, to); return PL_unify(t, to);
} else { } else {
char *s;
PyObject *pValR = PyObject_Repr(pVal); PyObject *pValR = PyObject_Repr(pVal);
if (pValR == NULL) if (pValR == NULL)
return address_to_term(pVal, t); return address_to_term(pVal, t);
#if PY_MAJOR_VERSION < 3
Py_ssize_t sz = PyUnicode_GetSize(pValR) + 1; Py_ssize_t sz = PyUnicode_GetSize(pValR) + 1;
#if PY_MAJOR_VERSION < 3
s = malloc(sizeof(char) * sz); s = malloc(sizeof(char) * sz);
PyObject *us = PyUnicode_EncodeUTF8((const Py_UNICODE *)pValR, sz, NULL); PyObject *us = PyUnicode_EncodeUTF8((const Py_UNICODE *)pValR, sz, NULL);
free(s);
PyString_AsStringAndSize(us, &s, &sz); PyString_AsStringAndSize(us, &s, &sz);
foreign_t rc = repr_term(s, sz, t);
free(s);
return rc;
#else #else
Py_ssize_t sz = PyUnicode_GetLength(pVal) + 1; // new interface
s = malloc(sizeof(char) * sz); char *s = PyUnicode_AsUTF8AndSize(pVal, &sz);
PyObject *obj = PyUnicode_AsUTF8Char(pVal, ptr, sz);
PyString_AsStringAndSize(obj, &s, &sz);
#endif
return repr_term(s, sz, t); return repr_term(s, sz, t);
#endif
} }
} }
@ -1485,15 +1486,14 @@ static int python_import(term_t mname, term_t mod) {
strcat(str, "."); strcat(str, ".");
strcat(str, s2); strcat(str, s2);
s = str; s = str;
} else if (!PL_get_nchars(mname, &len, &s, } else if (!PL_get_nchars(mname, &len, &s, CVT_ALL | CVT_EXCEPTION)) {
CVT_ALL | CVT_EXCEPTION)) {
return FALSE; return FALSE;
} }
#if PY_MAJOR_VERSION < 3 #if PY_MAJOR_VERSION < 3
pName = PyString_FromString(s); pName = PyString_FromString(s);
#else #else
printf("Module=%s\n",s); printf("Module=%s\n", s);
pName = PyUnicode_FromString(s); pName = PyUnicode_FromString(s);
#endif #endif
if (pName == NULL) { if (pName == NULL) {
return FALSE; return FALSE;
@ -1527,7 +1527,7 @@ static foreign_t python_f(term_t tmod, term_t fname, term_t tf) {
#if PY_MAJOR_VERSION < 3 #if PY_MAJOR_VERSION < 3
pName = PyString_FromString(s); pName = PyString_FromString(s);
#else #else
pName = PyUnicode_FromString(s); pName = PyUnicode_FromString(s);
#endif #endif
if (pName == NULL) { if (pName == NULL) {
return FALSE; return FALSE;
@ -1544,7 +1544,7 @@ static foreign_t python_f(term_t tmod, term_t fname, term_t tf) {
if (pF == NULL || !PyCallable_Check(pF)) { if (pF == NULL || !PyCallable_Check(pF)) {
return FALSE; return FALSE;
} }
printf("Module=%s ok\n",s); printf("Module=%s ok\n", s);
return python_to_ptr(pF, tf); return python_to_ptr(pF, tf);
} }
@ -1598,7 +1598,11 @@ static foreign_t python_index(term_t tobj, term_t tindex, term_t val) {
i = term_to_python(tindex); i = term_to_python(tindex);
if (i == NULL) if (i == NULL)
return false; return false;
#if PY_MAJOR_VERSION < 3
f = PyObject_CallMethodObjArgs(o, PyString_FromString("getitem"), i); f = PyObject_CallMethodObjArgs(o, PyString_FromString("getitem"), i);
#else
f = PyObject_CallMethodObjArgs(o, PyUnicode_FromString("getitem"), i);
#endif
return python_to_ptr(f, val); return python_to_ptr(f, val);
} }
@ -1611,81 +1615,78 @@ static foreign_t python_is(term_t tobj, term_t tf) {
return python_to_ptr(o, tf); return python_to_ptr(o, tf);
} }
static foreign_t python_assign_item(term_t parent, term_t indx, term_t tobj) { static foreign_t python_assign_item(term_t parent, term_t indx, term_t tobj) {
PyObject *pF, *pI; PyObject *pF, *pI;
PyObject *p; PyObject *p;
// get Scope ... // get Scope ...
pI = term_to_python(indx); pI = term_to_python(indx);
// got Scope.Exp // got Scope.Exp
// get Scope ... // get Scope ...
p = term_to_python(parent); p = term_to_python(parent);
// Exp // Exp
// get Scope ... // get Scope ...
pF = term_to_python(parent); pF = term_to_python(parent);
// Exp // Exp
if (!pI || !p) { if (!pI || !p) {
return false; return false;
} else if (PyObject_SetItem(p, pI,pF)) { } else if (PyObject_SetItem(p, pI, pF)) {
PyErr_Print(); PyErr_Print();
return FALSE; return FALSE;
} }
Py_DecRef(pI); Py_DecRef(pI);
Py_DecRef(p); Py_DecRef(p);
return true; return true;
} }
static foreign_t python_item(term_t parent, term_t indx, term_t tobj) { static foreign_t python_item(term_t parent, term_t indx, term_t tobj) {
PyObject *pF, *pI; PyObject *pF, *pI;
PyObject *p; PyObject *p;
// get Scope ... // get Scope ...
pI = term_to_python(indx); pI = term_to_python(indx);
// got Scope.Exp // got Scope.Exp
// get Scope ... // get Scope ...
p = term_to_python(parent); p = term_to_python(parent);
// Exp // Exp
if (!pI || !p) { if (!pI || !p) {
return false; return false;
} else if ((pF =PyObject_GetItem(p, pI)) == NULL) { } else if ((pF = PyObject_GetItem(p, pI)) == NULL) {
PyErr_Print(); PyErr_Print();
return FALSE; return FALSE;
} }
Py_DecRef(pI); Py_DecRef(pI);
Py_DecRef(p); Py_DecRef(p);
return address_to_term(pF, tobj); return address_to_term(pF, tobj);
} }
static foreign_t python_slice(term_t parent, term_t indx, term_t tobj) {
static foreign_t python_slice(term_t parent, term_t indx, term_t tobj) { PyObject *pF, *pI;
PyObject *pF, *pI;
PyObject *p;
PyObject *p;
// get Scope ...
// get Scope ... pI = term_to_python(indx);
pI = term_to_python(indx); // got Scope.Exp
// got Scope.Exp // get Scope ...
// get Scope ... p = term_to_python(parent);
p = term_to_python(parent); // Exp
// Exp if (!pI || !p) {
if (!pI || !p) { return false;
return false; } else if ((pF = PySequence_GetSlice(p, 0, 0)) == NULL) {
} else if ((pF =PySequence_GetSlice(p, 0, 0)) == NULL) { PyErr_Print();
PyErr_Print(); return FALSE;
return FALSE; }
} Py_DecRef(pI);
Py_DecRef(pI); Py_DecRef(p);
Py_DecRef(p);
return address_to_term(pF, tobj);
return address_to_term(pF, tobj); }
}
static foreign_t python_apply(term_t tin, term_t targs, term_t keywds, static foreign_t python_apply(term_t tin, term_t targs, term_t keywds,
term_t tf) { term_t tf) {
@ -1819,7 +1820,7 @@ static foreign_t python_builtin_eval(term_t caller, term_t dict, term_t out) {
return false; return false;
} }
} }
pOut = PyObject_CallObject((PyObject *)&PyFile_Type, pArgs); pOut = PyObject_CallObject(pI, pArgs);
Py_DECREF(pArgs); Py_DECREF(pArgs);
Py_DECREF(pI); Py_DECREF(pI);
if (pOut == NULL) { if (pOut == NULL) {
@ -1978,7 +1979,7 @@ static foreign_t array_to_python_list(term_t addr, term_t type, term_t szt,
} }
} }
if (PL_is_variable(py)) { if (PL_is_variable(py)) {
return python_to_ptr( list, py); return python_to_ptr(list, py);
} }
return assign_to_symbol(py, list); return assign_to_symbol(py, list);
} }
@ -2010,7 +2011,11 @@ static foreign_t array_to_python_tuple(term_t addr, term_t type, term_t szt,
int32_t *v = (int32_t *)src; int32_t *v = (int32_t *)src;
PyObject *x; PyObject *x;
for (i = 0; i < sz; i++) { for (i = 0; i < sz; i++) {
#if PY_MAJOR_VERSION < 3
x = PyInt_FromLong(v[i]); x = PyInt_FromLong(v[i]);
#else
x = PyLong_FromLong(v[i]);
#endif
if (PyTuple_SetItem(list, i, x)) { if (PyTuple_SetItem(list, i, x)) {
PyErr_Print(); PyErr_Print();
return FALSE; return FALSE;
@ -2065,8 +2070,15 @@ static foreign_t python_run_file(term_t file) {
char si[256]; char si[256];
s = si; s = si;
if (PL_get_nchars(file, &len, &s, CVT_ALL | CVT_EXCEPTION)) { if (PL_get_nchars(file, &len, &s, CVT_ALL | CVT_EXCEPTION)) {
#if PY_MAJOR_VERSION < 3
PyObject *PyFileObject = PyFile_FromString(si, "r"); PyObject *PyFileObject = PyFile_FromString(si, "r");
PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "test.py", 1); PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "test.py", 1);
#else
FILE *f = fopen(s, "r");
if (f == NULL)
return false;
PyRun_SimpleFileEx(f, s, 1);
#endif
return TRUE; return TRUE;
} }
return false; return false;
@ -2095,7 +2107,12 @@ static foreign_t python_run_script(term_t cmd, term_t fun) {
(s = sf) != NULL && (s = sf) != NULL &&
PL_get_nchars(fun, &len1, &s, CVT_ALL | CVT_EXCEPTION)) { PL_get_nchars(fun, &len1, &s, CVT_ALL | CVT_EXCEPTION)) {
#if PY_MAJOR_VERSION < 3
pName = PyString_FromString("rbm"); pName = PyString_FromString("rbm");
#else
// asssumes UTF-8
pName = PyUnicode_FromString("rbm");
#endif
/* Error checking of pName left out */ /* Error checking of pName left out */
pModule = PyImport_Import(pName); pModule = PyImport_Import(pName);
@ -2108,7 +2125,6 @@ static foreign_t python_run_script(term_t cmd, term_t fun) {
if (pFunc && PyCallable_Check(pFunc)) { if (pFunc && PyCallable_Check(pFunc)) {
pValue = PyObject_CallObject(pFunc, pArgs); pValue = PyObject_CallObject(pFunc, pArgs);
if (pValue != NULL) { if (pValue != NULL) {
printf("Result of call: %ld\n", PyInt_AsLong(pValue));
Py_DECREF(pValue); Py_DECREF(pValue);
} else { } else {
Py_DECREF(pFunc); Py_DECREF(pFunc);
@ -2143,7 +2159,12 @@ static foreign_t init_python(void) {
char **argv; char **argv;
term_t t = PL_new_term_ref(); term_t t = PL_new_term_ref();
YAP_Argv(&argv); YAP_Argv(&argv);
#if PY_MAJOR_VERSION < 3
Py_SetProgramName(argv[0]); Py_SetProgramName(argv[0]);
#else
wchar_t *buf = Py_DecodeLocale(argv[0], NULL);
Py_SetProgramName(buf);
#endif
Py_Initialize(); Py_Initialize();
py_Main = PyImport_AddModule("__main__"); py_Main = PyImport_AddModule("__main__");
py_Builtin = PyImport_AddModule("__builtin__"); py_Builtin = PyImport_AddModule("__builtin__");
@ -2227,6 +2248,3 @@ install_t install_libpython(void) {
PL_register_foreign("python_builtin_eval", 3, python_builtin_eval, 0); PL_register_foreign("python_builtin_eval", 3, python_builtin_eval, 0);
PL_register_foreign("python_builtin", 1, python_builtin, 0); PL_register_foreign("python_builtin", 1, python_builtin, 0);
} }

View File

@ -0,0 +1,50 @@
# python commands
import sys
import yap
#
# initialize engine
engine = yap.YAPEngine();
# engine = yap.YAPEngine(yap.YAPParams());
def query( s ):
q = engine.query(s)
while q.next():
vs = q.namedVars()
if vs.length() == 0:
print( "yes" )
return
else:
while vs.length() > 0:
eq = vs.car()
print( eq.getArg(1).text() + " = " + eq.getArg(2).text() )
vs = vs.cdr()
if q.deterministic():
return
s = input("next: ?")
if s.find(';') != 0 :
return
print( "no more answers" )
return
def live():
loop = True
while loop:
try:
s = input("?- ")
query( s )
except SyntaxError as err:
print("Syntax Error error: {0}".format(err))
except EOFError:
return
except RuntimeError as err:
print("YAP Execution Error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
live()

View File

@ -41,7 +41,7 @@ specifying the object files to load, _Libs_ is a list (possibly
empty) of libraries to be passed to the unix loader (`ld`) and empty) of libraries to be passed to the unix loader (`ld`) and
InitRoutine is the name of the C routine (to be called after the files InitRoutine is the name of the C routine (to be called after the files
are loaded) to perform the necessary declarations to YAP of the are loaded) to perform the necessary declarations to YAP of the
predicates defined in the files. predicates defined in the files.
YAP will search for _ObjectFiles_ in the current directory first. If YAP will search for _ObjectFiles_ in the current directory first. If
it cannot find them it will search for the files using the environment it cannot find them it will search for the files using the environment
@ -59,7 +59,7 @@ load_foreign_files(Objs,Libs,Entry) :-
'$check_objs_for_load_foreign_files'(Objs,NewObjs,load_foreign_files(Objs,Libs,Entry)), '$check_objs_for_load_foreign_files'(Objs,NewObjs,load_foreign_files(Objs,Libs,Entry)),
'$check_libs_for_load_foreign_files'(Libs,NewLibs,load_foreign_files(Objs,Libs,Entry)), '$check_libs_for_load_foreign_files'(Libs,NewLibs,load_foreign_files(Objs,Libs,Entry)),
'$check_entry_for_load_foreign_files'(Entry,load_foreign_files(Objs,Libs,Entry)), '$check_entry_for_load_foreign_files'(Entry,load_foreign_files(Objs,Libs,Entry)),
( (
recordzifnot( '$foreign', M:'$foreign'(Objs,Libs,Entry), _) recordzifnot( '$foreign', M:'$foreign'(Objs,Libs,Entry), _)
-> ->
'$load_foreign_files'(NewObjs,NewLibs,Entry), '$load_foreign_files'(NewObjs,NewLibs,Entry),
@ -71,9 +71,9 @@ load_foreign_files(Objs,Libs,Entry) :-
true true
) )
; ;
true true
), ),
!. !.
/** @pred load_absolute_foreign_files( _Files_, _Libs_, _InitRoutine_) /** @pred load_absolute_foreign_files( _Files_, _Libs_, _InitRoutine_)
@ -82,7 +82,7 @@ Loads object files produced by the C compiler. It is useful when no search shoul
*/ */
load_absolute_foreign_files(Objs,Libs,Entry) :- load_absolute_foreign_files(Objs,Libs,Entry) :-
source_module(M), source_module(M),
( (
recordzifnot( '$foreign', M:'$foreign'(Objs,Libs,Entry), _) recordzifnot( '$foreign', M:'$foreign'(Objs,Libs,Entry), _)
-> ->
'$load_foreign_files'(Objs,Libs,Entry), '$load_foreign_files'(Objs,Libs,Entry),
@ -94,7 +94,7 @@ load_absolute_foreign_files(Objs,Libs,Entry) :-
true true
) )
; ;
true true
), ),
!. !.
@ -176,7 +176,7 @@ On errors, an exception `shared_object`( _Action_,
_Message_) is raised. _Message_ is the return value from _Message_) is raised. _Message_ is the return value from
dlerror(). dlerror().
*/ */
open_shared_object(File, Handle) :- open_shared_object(File, Handle) :-
open_shared_object(File, [], Handle). open_shared_object(File, [], Handle).
@ -185,15 +185,15 @@ open_shared_object(File, Handle) :-
As `open_shared_object/2`, but allows for additional flags to As `open_shared_object/2`, but allows for additional flags to
be passed. _Options_ is a list of atoms. `now` implies the be passed. _Options_ is a list of atoms. `now` implies the
symbols are symbols are
resolved immediately rather than lazily (default). `global` implies resolved immediately rather than lazily (default). `global` implies
symbols of the loaded object are visible while loading other shared symbols of the loaded object are visible while loading other shared
objects (by default they are local). Note that these flags may not objects (by default they are local). Note that these flags may not
be supported by your operating system. Check the documentation of be supported by your operating system. Check the documentation of
`dlopen()` or equivalent on your operating system. Unsupported `dlopen()` or equivalent on your operating system. Unsupported
flags are silently ignored. flags are silently ignored.
*/ */
open_shared_object(File, Opts, Handle) :- open_shared_object(File, Opts, Handle) :-
'$open_shared_opts'(Opts, open_shared_object(File, Opts, Handle), OptsI), '$open_shared_opts'(Opts, open_shared_object(File, Opts, Handle), OptsI),
@ -209,7 +209,7 @@ open_shared_object(File, Opts, Handle) :-
'$open_shared_opts'(Opts, G, V0), '$open_shared_opts'(Opts, G, V0),
'$open_shared_opt'(Opt, G, OptV), '$open_shared_opt'(Opt, G, OptV),
V0 is V \/ OptV. V0 is V \/ OptV.
'$open_shared_opt'(Opt, G, _) :- '$open_shared_opt'(Opt, G, _) :-
var(Opt), !, var(Opt), !,
'$do_error'(instantiation_error,G). '$do_error'(instantiation_error,G).
@ -217,7 +217,7 @@ open_shared_object(File, Opts, Handle) :-
'$open_shared_opt'(global, __, 2) :- !. '$open_shared_opt'(global, __, 2) :- !.
'$open_shared_opt'(Opt, Goal, _) :- '$open_shared_opt'(Opt, Goal, _) :-
'$do_error'(domain_error(open_shared_object_option,Opt),Goal). '$do_error'(domain_error(open_shared_object_option,Opt),Goal).
/** @pred call_shared_object_function(+ _Handle_, + _Function_) /** @pred call_shared_object_function(+ _Handle_, + _Function_)
Call the named function in the loaded shared library. The function is Call the named function in the loaded shared library. The function is
@ -233,3 +233,11 @@ call_shared_object_function( Handle, Function) :-
ignore( recordzifnot( '$foreign', M:'$swi_foreign'( Handle, Function ), _) ). ignore( recordzifnot( '$foreign', M:'$swi_foreign'( Handle, Function ), _) ).
%% @} %% @}
/** @pred $slave is det
Called at boot-time when Prolog is run from another language (eg, Java, Python, Android)
*/
'$slave' :-
getenv( '__PYVENV_LAUNCHER__', _ ),
use_module( library(python) ).