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)
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( NO_POLICY_SCOPE )
endif()

View File

@ -445,8 +445,6 @@ YAPQuery::YAPQuery(YAPPredicate p, YAPTerm ts[]) : YAPPredicate(p.ap) {
YAPListTerm YAPQuery::namedVars() {
CACHE_REGS
Term o = vnames.term();
Yap_DebugPlWrite(o);
printf("<<<<<<<<<<<<<<<<-------------------------\n");
return o; // should be o
}
@ -454,9 +452,6 @@ bool YAPQuery::next() {
CACHE_REGS
int result;
Yap_DebugPlWrite(vnames.term());
fprintf(stderr, "++++++++++++++\n");
BACKUP_MACHINE_REGS();
if (q_open != 1)
return false;
@ -464,17 +459,15 @@ bool YAPQuery::next() {
return false;
// don't forget, on success these guys must create slots
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);
Yap_DebugPlWrite(Yap_GetFromSlot(q_g));
fprintf(stderr, "+++++ ap=%d +++++++++\n", result);
} else {
LOCAL_AllowRestart = q_open;
result = (bool)YAP_RetryGoal(&q_h);
}
q_state = 1;
if (Yap_GetException()) {
throw(YAPError(SYSTEM_ERROR_INTERNAL));
}
if (!result) {
YAP_LeaveGoal(FALSE, &q_h);
q_open = 0;
@ -495,6 +488,17 @@ void YAPQuery::cut() {
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() {
CACHE_REGS
@ -595,12 +599,7 @@ YAPEngine::YAPEngine(char *savedState, size_t stackSize, size_t trailSize,
init_args.YapPrologBootFile = bootFile;
init_args.YapPrologGoal = goal;
init_args.YapPrologTopLevelGoal = topLevel;
init_args.HaltAfter
= script;
init_args.HaltAfterConsult = script;
init_args.FastBoot = fastBoot;
yerror = YAPError();
delYAPCallback();

View File

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

View File

@ -58,6 +58,9 @@ public:
/// ask for the next solution of the current query
/// same call for every solution
bool next();
/// does this query have open choice-points?
/// or is it deterministic?
bool deterministic();
/// represent the top-goal
const char *text();
/// 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
#define YAPT_HH 1
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

View File

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

View File

@ -47,9 +47,6 @@
#endif /* THREADS && (YAPOR_COW || YAPOR_SBA || YAPOR_COPY) */
// Bad export from Python
#ifdef HAVE_STAT
#undef HAVE_STAT
#endif
#include "config.h"
#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_Reset(YAP_FULL_RESET);
/* End preprocessor code */

View File

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

View File

@ -31,15 +31,15 @@ ENDIF(MSVC)
set_source_files_properties(${outfile} PROPERTIES GENERATED TRUE)
endfunction()
Add_custom_target (plmyddas ALL DEPENDS ${MYDDAS_YPP} ) # WORKING_DIRECTORY ${CMAKE_BINARY_DIR} )
foreach(file ${MYDDAS_YPP})
cpp_compile( MYDDAS_YAP ${file})
#message("outfiles=${MYDDAS_YAP}\n")
endforeach()
Add_custom_target (plmyddas ALL DEPENDS ${MYDDAS_YPP} ${MYDDAS_YAP} ) # WORKING_DIRECTORY ${CMAKE_BINARY_DIR} )
install(FILES ${MYDDAS_YAP}
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_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
# PYTHON_LIBRARIES - path to the python library

View File

@ -438,8 +438,8 @@ static PyObject *bip_sum(term_t t) {
return NULL;
}
Py_INCREF(result);
}
#endif
}
#ifndef SLOW_SUM
/* 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)) {
PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
f_result += (double)PyInt_AS_LONG(item);
PyFPE_END_PROTECT(f_result) Py_DECREF(item);
continue;
}
#else
if (PyLong_CheckExact(item)) {
PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
f_result += PyLong_AsDouble(item);
#endif
PyFPE_END_PROTECT(f_result) Py_DECREF(item);
continue;
}
#endif
result = PyFloat_FromDouble(f_result);
temp = PyNumber_Add(result, item);
Py_DECREF(result);
@ -539,8 +542,8 @@ to the more general routine.
return NULL;
}
}
}
#endif
}
for (;;) {
item = PyIter_Next(iter);
@ -1430,24 +1433,22 @@ static foreign_t python_to_term(PyObject *pVal, term_t t) {
PL_cons_functor(to, FUNCTOR_curly1, to);
return PL_unify(t, to);
} else {
char *s;
PyObject *pValR = PyObject_Repr(pVal);
if (pValR == NULL)
return address_to_term(pVal, t);
#if PY_MAJOR_VERSION < 3
Py_ssize_t sz = PyUnicode_GetSize(pValR) + 1;
#if PY_MAJOR_VERSION < 3
s = malloc(sizeof(char) * sz);
PyObject *us = PyUnicode_EncodeUTF8((const Py_UNICODE *)pValR, sz, NULL);
free(s);
PyString_AsStringAndSize(us, &s, &sz);
foreign_t rc = repr_term(s, sz, t);
free(s);
return rc;
#else
Py_ssize_t sz = PyUnicode_GetLength(pVal) + 1;
s = malloc(sizeof(char) * sz);
PyObject *obj = PyUnicode_AsUTF8Char(pVal, ptr, sz);
PyString_AsStringAndSize(obj, &s, &sz);
#endif
// new interface
char *s = PyUnicode_AsUTF8AndSize(pVal, &sz);
return repr_term(s, sz, t);
#endif
}
}
@ -1485,14 +1486,13 @@ static int python_import(term_t mname, term_t mod) {
strcat(str, ".");
strcat(str, s2);
s = str;
} else if (!PL_get_nchars(mname, &len, &s,
CVT_ALL | CVT_EXCEPTION)) {
} else if (!PL_get_nchars(mname, &len, &s, CVT_ALL | CVT_EXCEPTION)) {
return FALSE;
}
#if PY_MAJOR_VERSION < 3
pName = PyString_FromString(s);
#else
printf("Module=%s\n",s);
printf("Module=%s\n", s);
pName = PyUnicode_FromString(s);
#endif
if (pName == NULL) {
@ -1544,7 +1544,7 @@ static foreign_t python_f(term_t tmod, term_t fname, term_t tf) {
if (pF == NULL || !PyCallable_Check(pF)) {
return FALSE;
}
printf("Module=%s ok\n",s);
printf("Module=%s ok\n", s);
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);
if (i == NULL)
return false;
#if PY_MAJOR_VERSION < 3
f = PyObject_CallMethodObjArgs(o, PyString_FromString("getitem"), i);
#else
f = PyObject_CallMethodObjArgs(o, PyUnicode_FromString("getitem"), i);
#endif
return python_to_ptr(f, val);
}
@ -1612,7 +1616,7 @@ static foreign_t python_is(term_t tobj, term_t 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 *p;
@ -1628,7 +1632,7 @@ static foreign_t python_is(term_t tobj, term_t tf) {
// Exp
if (!pI || !p) {
return false;
} else if (PyObject_SetItem(p, pI,pF)) {
} else if (PyObject_SetItem(p, pI, pF)) {
PyErr_Print();
return FALSE;
}
@ -1636,9 +1640,9 @@ static foreign_t python_is(term_t tobj, term_t tf) {
Py_DecRef(p);
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 *p;
@ -1651,7 +1655,7 @@ static foreign_t python_is(term_t tobj, term_t tf) {
// Exp
if (!pI || !p) {
return false;
} else if ((pF =PyObject_GetItem(p, pI)) == NULL) {
} else if ((pF = PyObject_GetItem(p, pI)) == NULL) {
PyErr_Print();
return FALSE;
}
@ -1659,10 +1663,9 @@ static foreign_t python_is(term_t tobj, term_t tf) {
Py_DecRef(p);
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 *p;
@ -1675,7 +1678,7 @@ static foreign_t python_is(term_t tobj, term_t tf) {
// Exp
if (!pI || !p) {
return false;
} else if ((pF =PySequence_GetSlice(p, 0, 0)) == NULL) {
} else if ((pF = PySequence_GetSlice(p, 0, 0)) == NULL) {
PyErr_Print();
return FALSE;
}
@ -1683,9 +1686,7 @@ static foreign_t python_is(term_t tobj, term_t tf) {
Py_DecRef(p);
return address_to_term(pF, tobj);
}
}
static foreign_t python_apply(term_t tin, term_t targs, term_t keywds,
term_t tf) {
@ -1819,7 +1820,7 @@ static foreign_t python_builtin_eval(term_t caller, term_t dict, term_t out) {
return false;
}
}
pOut = PyObject_CallObject((PyObject *)&PyFile_Type, pArgs);
pOut = PyObject_CallObject(pI, pArgs);
Py_DECREF(pArgs);
Py_DECREF(pI);
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)) {
return python_to_ptr( list, py);
return python_to_ptr(list, py);
}
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;
PyObject *x;
for (i = 0; i < sz; i++) {
#if PY_MAJOR_VERSION < 3
x = PyInt_FromLong(v[i]);
#else
x = PyLong_FromLong(v[i]);
#endif
if (PyTuple_SetItem(list, i, x)) {
PyErr_Print();
return FALSE;
@ -2065,8 +2070,15 @@ static foreign_t python_run_file(term_t file) {
char si[256];
s = si;
if (PL_get_nchars(file, &len, &s, CVT_ALL | CVT_EXCEPTION)) {
#if PY_MAJOR_VERSION < 3
PyObject *PyFileObject = PyFile_FromString(si, "r");
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 false;
@ -2095,7 +2107,12 @@ static foreign_t python_run_script(term_t cmd, term_t fun) {
(s = sf) != NULL &&
PL_get_nchars(fun, &len1, &s, CVT_ALL | CVT_EXCEPTION)) {
#if PY_MAJOR_VERSION < 3
pName = PyString_FromString("rbm");
#else
// asssumes UTF-8
pName = PyUnicode_FromString("rbm");
#endif
/* Error checking of pName left out */
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)) {
pValue = PyObject_CallObject(pFunc, pArgs);
if (pValue != NULL) {
printf("Result of call: %ld\n", PyInt_AsLong(pValue));
Py_DECREF(pValue);
} else {
Py_DECREF(pFunc);
@ -2143,7 +2159,12 @@ static foreign_t init_python(void) {
char **argv;
term_t t = PL_new_term_ref();
YAP_Argv(&argv);
#if PY_MAJOR_VERSION < 3
Py_SetProgramName(argv[0]);
#else
wchar_t *buf = Py_DecodeLocale(argv[0], NULL);
Py_SetProgramName(buf);
#endif
Py_Initialize();
py_Main = PyImport_AddModule("__main__");
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", 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

@ -233,3 +233,11 @@ call_shared_object_function( 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) ).