dynamic loading

This commit is contained in:
Vitor Santos Costa 2017-11-08 10:29:01 +01:00
parent 9100e797f8
commit 538cb4eb2c
15 changed files with 206 additions and 228 deletions

View File

@ -76,7 +76,8 @@ char *Yap_FindExecutable(void) {
if (!_NSGetExecutablePath(buf, &size)) { if (!_NSGetExecutablePath(buf, &size)) {
buf = realloc(buf, size + 1); buf = realloc(buf, size + 1);
return buf; return buf;
} return "yap"; }
return "yap";
#elif defined(__linux__) #elif defined(__linux__)
enum { BUFFERSIZE = 1024 }; enum { BUFFERSIZE = 1024 };
char *buf = malloc(BUFFERSIZE); char *buf = malloc(BUFFERSIZE);
@ -164,10 +165,10 @@ static Int LoadForeign(StringList ofiles, StringList libs, char *proc_name,
CACHE_REGS CACHE_REGS
LOCAL_ErrorMessage = NULL; LOCAL_ErrorMessage = NULL;
while (libs) { while (libs) {
const char *file = AtomName(libs->name); const char *file = AtomName(libs->name);
if (!Yap_findFile(file, NULL, NULL, LOCAL_FileNameBuf, true, YAP_OBJ, true, true)) { if (!Yap_findFile(file, NULL, NULL, LOCAL_FileNameBuf, true, YAP_OBJ, true,
true)) {
LOCAL_ErrorMessage = malloc(MAX_ERROR_MSG_SIZE); LOCAL_ErrorMessage = malloc(MAX_ERROR_MSG_SIZE);
/* use LD_LIBRARY_PATH */ /* use LD_LIBRARY_PATH */
strncpy(LOCAL_ErrorMessage, (char *)AtomName(libs->name), strncpy(LOCAL_ErrorMessage, (char *)AtomName(libs->name),
@ -184,19 +185,19 @@ static Int LoadForeign(StringList ofiles, StringList libs, char *proc_name,
if (LOCAL_ErrorMessage == NULL) { if (LOCAL_ErrorMessage == NULL) {
LOCAL_ErrorMessage = malloc(MAX_ERROR_MSG_SIZE); LOCAL_ErrorMessage = malloc(MAX_ERROR_MSG_SIZE);
strcpy(LOCAL_ErrorMessage, dlerror()); strcpy(LOCAL_ErrorMessage, dlerror());
} } }
}
libs = libs->next; libs = libs->next;
} }
while (ofiles) { while (ofiles) {
void *handle;
/* load libraries first so that their symbols are available to /* load libraries first so that their symbols are available to
other routines */ other routines */
/* dlopen wants to follow the LD_CONFIG_PATH */ /* dlopen wants to follow the LD_CONFIG_PATH */
const char *file = AtomName(ofiles->name); const char *file = AtomName(ofiles->name);
if (!Yap_findFile(file, NULL, NULL, LOCAL_FileNameBuf, true, YAP_OBJ, true, true)) { if (!Yap_findFile(file, NULL, NULL, LOCAL_FileNameBuf, true, YAP_OBJ, true,
true)) {
if (LOCAL_ErrorMessage == NULL) { if (LOCAL_ErrorMessage == NULL) {
LOCAL_ErrorMessage = malloc(MAX_ERROR_MSG_SIZE); LOCAL_ErrorMessage = malloc(MAX_ERROR_MSG_SIZE);
strcpy(LOCAL_ErrorMessage, strcpy(LOCAL_ErrorMessage,
@ -204,9 +205,10 @@ static Int LoadForeign(StringList ofiles, StringList libs, char *proc_name,
} }
} }
#ifdef __osf__ #ifdef __osf__
if ((handle = dlopen(LOCAL_FileNameBuf, RTLD_LAZY)) == 0) if ((ofiles->handle = dlopen(LOCAL_FileNameBuf, RTLD_LAZY)) == NULL)
#elseö #else
if ((handle = dlopen(LOCAL_FileNameBuf, RTLD_LAZY | RTLD_GLOBAL)) == 0) if ((ofiles->handle = dlopen(LOCAL_FileNameBuf, RTLD_LAZY | RTLD_GLOBAL)) ==
NULL)
#endif #endif
{ {
if (LOCAL_ErrorMessage == NULL) { if (LOCAL_ErrorMessage == NULL) {
@ -216,17 +218,14 @@ static Int LoadForeign(StringList ofiles, StringList libs, char *proc_name,
} }
} }
ofiles->handle = handle; if (ofiles->handle && proc_name && !*init_proc)
*init_proc = (YapInitProc)dlsym(ofiles->handle, proc_name);
if (proc_name && !*init_proc)
*init_proc = (YapInitProc)dlsym(handle, proc_name);
ofiles = ofiles->next; ofiles = ofiles->next;
} }
if (!*init_proc && LOCAL_ErrorMessage == NULL) { if (!*init_proc && LOCAL_ErrorMessage == NULL) {
char *buf = malloc(1058); char *buf = malloc(1058);
snprintf(buf,1058-1, snprintf(buf, 1058 - 1, "Could not locate routine %s in %s: %s\n",
"Could not locate routine %s in %s: %s\n",
proc_name, LOCAL_FileNameBuf, dlerror()); proc_name, LOCAL_FileNameBuf, dlerror());
return LOAD_FAILLED; return LOAD_FAILLED;
} }

View File

@ -274,7 +274,7 @@ static void writebig(Term t, int p, int depth, int rinfixarg,
YAP_Opaque_CallOnWrite f; YAP_Opaque_CallOnWrite f;
CELL blob_info; CELL blob_info;
blob_info = big_tag - USER_BLOB_START; blob_info = big_tag;
if (GLOBAL_OpaqueHandlers && if (GLOBAL_OpaqueHandlers &&
(f = GLOBAL_OpaqueHandlers[blob_info].write_handler)) { (f = GLOBAL_OpaqueHandlers[blob_info].write_handler)) {
(f)(wglb->stream->file, big_tag, ExternalBlobFromTerm(t), 0); (f)(wglb->stream->file, big_tag, ExternalBlobFromTerm(t), 0);

View File

@ -2,10 +2,6 @@
# value of 3.4.0 or lower. # value of 3.4.0 or lower.
cmake_minimum_required(VERSION 3.4) cmake_minimum_required(VERSION 3.4)
if(COMMAND cmake_policy)
cmake_policy(SET CMP0003 NEW)
endif(COMMAND cmake_policy)
# Sets the version of CMake required to build the native # Sets the version of CMake required to build the native
# library. You should either keep the default value or pass a # library. You should either keep the default value or pass a
# value of 3.4.0 or lower. # value of 3.4.0 or lower.
@ -65,7 +61,15 @@ if(NOT COMMAND find_host_program)
endmacro() endmacro()
endif() endif()
if (POLICY CMP0003)
cmake_policy(SET CMP0003 NEW)
endif()
if (POLICY CMP0068)
cmake_policy(SET CMP0068 NEW)
endif()
option(BUILD_SHARED_LIBS "Build shared library" ON) option(BUILD_SHARED_LIBS "Build shared library" ON)
set (CMAKE_POSITION_INDEPENDENT_CODE TRUE) set (CMAKE_POSITION_INDEPENDENT_CODE TRUE)
set (CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE) set (CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE)
@ -87,18 +91,18 @@ function(add_to_group list output)
endfunction(add_to_group list output ) endfunction(add_to_group list output )
function(add_to_libgroup el list) function(add_to_libgroup el list)
add_custom_command( TARGET ${el} POST_BUILD # add_custom_command( TARGET ${el} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:${el}> ${CMAKE_BINARY_DIR}/packages/python/swig/yap4py # COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:${el}> ${CMAKE_BINARY_DIR}/packages/python/swig/yap4py
DEPENDS ${el} ) # DEPENDS ${el} )
list( APPEND ${list} ${${el}}) list( APPEND ${list} ${${el}})
set (${list} ${${list}} CACHE INTERNAL "prolog dll files") set (${list} ${${list}} CACHE INTERNAL "prolog dll files")
endfunction(add_to_libgroup el list ) endfunction(add_to_libgroup el list )
function(add_to_corelibgroup el list) function(add_to_corelibgroup el list)
add_custom_command( TARGET ${el} POST_BUILD # add_custom_command( TARGET ${el} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:${el}> $<TARGET_SONAME_FILE:${el}> $<TARGET_LINKER_FILE:${el}> ${CMAKE_BINARY_DIR}/packages/python/swig/yap4py # COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:${el}> $<TARGET_SONAME_FILE:${el}> $<TARGET_LINKER_FILE:${el}> ${CMAKE_BINARY_DIR}/packages/python/swig/yap4py
DEPENDS ${el} ) # DEPENDS ${el} )
list( APPEND ${list} ${${el}}) list( APPEND ${list} ${${el}})
set (${list} ${${list}} CACHE INTERNAL "prolog dll files") set (${list} ${${list}} CACHE INTERNAL "prolog dll files")
endfunction(add_to_corelibgroup el list ) endfunction(add_to_corelibgroup el list )
@ -205,8 +209,11 @@ include(disallow)
disallow_intree_builds() disallow_intree_builds()
# set(CMAKE_BUILD_TYPE Debug) # set(CMAKE_BUILD_TYPE Debug)
set (ANACONDA $ENV{CONDA_PY})
if (APPLE) if (ANACONDA)
elseif (APPLE)
set (MACOSX_RPATH ON) set (MACOSX_RPATH ON)
set (PATH $ENV{PATH}) set (PATH $ENV{PATH})
list (FIND ${PATH} pos /usr/local) list (FIND ${PATH} pos /usr/local)
@ -223,7 +230,8 @@ if (APPLE)
/usr/local/opt/readline /usr/local/opt/readline
/usr/local/opt/swig /usr/local/opt/swig
) )
endif (APPLE ) endif ( )
if(ANDROID) if(ANDROID)
set ( datarootdir /assets ) set ( datarootdir /assets )
endif() endif()
@ -521,24 +529,23 @@ set_property(DIRECTORY PROPERTY CXX_STANDARD 11)
# rpath stuff, hopefully it works # rpath stuff, hopefully it works
# use, i.e. don't skip the full RPATH for the build tree # use, i.e. don't skip the full RPATH for the build tree
SET(CMAKE_SKIP_BUILD_RPATH FALSE) # SET(CMAKE_SKIP_BUILD_RPATH FALSE)
# when building, don't use the install RPATH already # when building, don't use the install RPATH already
# (but later on when installing) # (but later on when installing)
SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) # SET(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
SET(CMAKE_INSTALL_RPATH "${libdir}") # SET(CMAKE_INSTALL_RPATH ${CMAKE_CURRENT_BUILD_PATH})
# add the automatically determined parts of the RPATH # add the automatically determined parts of the RPATH
# which point to directories outside the build tree to the install RPATH # which point to directories outside the build tree to the install RPATH
SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) # SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
# the RPATH to be used when installing, but only if it's not a system directory # the RPATH to be used when installing, but only if it's not a system directory#LIST(FIND CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES "${libdir}" isSystemDir)
LIST(FIND CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES "${libdir}" isSystemDir) # IF("${isSystemDir}" STREQUAL "-1")
IF("${isSystemDir}" STREQUAL "-1") # SET(CMAKE_INSTALL_RPATH "${libdir}")
SET(CMAKE_INSTALL_RPATH "${libdir}") # ENDIF("${isSystemDir}" STREQUAL "-1")
ENDIF("${isSystemDir}" STREQUAL "-1")
include_directories (H include_directories (H
H/generated H/generated
@ -595,7 +602,7 @@ set_target_properties(libYap
PROPERTIES OUTPUT_NAME Yap PROPERTIES OUTPUT_NAME Yap
) )
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/packages/python/swig/yap4py) # file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/packages/python/swig/yap4py)
if (PYTHONLIBS_FOUND AND SWIG_FOUND) if (PYTHONLIBS_FOUND AND SWIG_FOUND)
add_subdirectory(packages/python/swig) add_subdirectory(packages/python/swig)

View File

@ -1,3 +1,4 @@
#ifdef FROZEN_STACKS #ifdef FROZEN_STACKS
{ {
tr_fr_ptr pt0, pt1, pbase, ptop; tr_fr_ptr pt0, pt1, pbase, ptop;
@ -31,7 +32,7 @@
Term t = HeadOfTerm(d1); Term t = HeadOfTerm(d1);
Functor f = FunctorOfTerm(t); Functor f = FunctorOfTerm(t);
if (f == FunctorBigInt) { if (f == FunctorBigInt) {
Int tag = Yap_blob_tag(t) - USER_BLOB_START; Int tag = Yap_blob_tag(t);
GLOBAL_OpaqueHandlers[tag].cut_handler(d1); GLOBAL_OpaqueHandlers[tag].cut_handler(d1);
} else { } else {
pt0--; pt0--;

View File

@ -248,7 +248,10 @@ check_function_exists(iswblank HAVE_ISWBLANK)
check_function_exists(iswspace HAVE_ISWSPACE) check_function_exists(iswspace HAVE_ISWSPACE)
check_symbol_exists(flsl <string.h> HAVE_FLSL) check_symbol_exists(flsl <string.h> HAVE_FLSL)
check_symbol_exists(flsll <string.h> HAVE_FLSLL) check_symbol_exists(flsll <string.h> HAVE_FLSLL)
if (NOT APPLE)
# only recently available
check_function_exists(fmemopen HAVE_FMEMOPEN) check_function_exists(fmemopen HAVE_FMEMOPEN)
endif()
check_function_exists(fpclass HAVE_FPCLASS) check_function_exists(fpclass HAVE_FPCLASS)
check_function_exists(fpurge HAVE_FPURGE) check_function_exists(fpurge HAVE_FPURGE)
check_function_exists(ftime HAVE_FTIME) check_function_exists(ftime HAVE_FTIME)

View File

@ -222,13 +222,16 @@ X_API int PL_get_nchars(term_t l, size_t *lengthp, char **s, unsigned flags) {
if (s) { if (s) {
size_t len = strlen(out.val.c); size_t len = strlen(out.val.c);
if (flags & (BUF_DISCARDABLE | BUF_RING)) { if (flags & (BUF_DISCARDABLE | BUF_RING)) {
pop_text_stack(lvl);
return true; return true;
} }
*s = pop_output_text_stack(lvl, out.val.c);
if (*s == out.val.c) { if (*s == out.val.c) {
char *v = malloc(len+1); pop_text_stack(lvl);
strcpy(v, *s); } else if (*s == NULL) {
*s = v; *s = pop_output_text_stack(lvl, out.val.c);
} else {
strcpy(*s, out.val.c);
pop_text_stack(lvl);
} }
if (lengthp) if (lengthp)
*lengthp = len; *lengthp = len;

View File

@ -916,7 +916,7 @@ namedvars InitNamedVars(int varcnt, int varstart) {
int i; int i;
temp.varcnt = varcnt; temp.varcnt = varcnt;
temp.varstart = varstart; temp.varstart = varstart;
temp.vars = (const char **)malloc(sizeof(char *) * varcnt); temp.vars = (char **)malloc(sizeof(char *) * varcnt);
temp.loaded = (int *)malloc(sizeof(int) * varcnt); temp.loaded = (int *)malloc(sizeof(int) * varcnt);
temp.dvalue = (double *)malloc(sizeof(double) * varcnt); temp.dvalue = (double *)malloc(sizeof(double) * varcnt);
temp.ivalue = (int *)malloc(sizeof(int) * varcnt); temp.ivalue = (int *)malloc(sizeof(int) * varcnt);
@ -933,7 +933,7 @@ namedvars InitNamedVars(int varcnt, int varstart) {
void EnlargeNamedVars(namedvars *varmap, int newvarcnt) { void EnlargeNamedVars(namedvars *varmap, int newvarcnt) {
int i; int i;
varmap->vars = (const char **)realloc(varmap->vars, sizeof(const char *) * newvarcnt); varmap->vars = (char **)realloc(varmap->vars, sizeof(const char *) * newvarcnt);
varmap->loaded = (int *)realloc(varmap->loaded, sizeof(int) * newvarcnt); varmap->loaded = (int *)realloc(varmap->loaded, sizeof(int) * newvarcnt);
varmap->dvalue = varmap->dvalue =
(double *)realloc(varmap->dvalue, sizeof(double) * newvarcnt); (double *)realloc(varmap->dvalue, sizeof(double) * newvarcnt);

View File

@ -95,9 +95,9 @@ tabled_complex_to_andor(IN, Map, Map, Tab, Tab, 1) :-
IN = !. IN = !.
tabled_complex_to_andor([Els], Map0, MapF, Tab0, TabF, V) :- tabled_complex_to_andor([Els], Map0, MapF, Tab0, TabF, V) :-
tabled_complex_to_and(Els, Map0, MapF, Tab0, TabF, V). tabled_complex_to_and(Els, Map0, MapF, Tab0, TabF, V).
tabled_complex_to_andor([El1,Dl2], Map0, MapF, Tab0, TabF, or(T1,T2)) :- tabled_complex_to_andor([El1,El2|Els], Map0, MapF, Tab0, TabF, or(T1,T2)) :-
tabled_complex_to_and(El1, Map0, MapI, Tab1, TabI, T1), tabled_complex_to_and(El1, Map0, MapI, Tab0, TabI, T1),
tabled_complex_to_andor(El2.Els, MapI, MapF, TabI, TabF, T2). tabled_complex_to_andor([El2|Els], MapI, MapF, TabI, TabF, T2).
tabled_complex_to_and(int(A1,[endlist]), Map0, MapF, Tab, Tab, V) :- !, tabled_complex_to_and(int(A1,[endlist]), Map0, MapF, Tab, Tab, V) :- !,
check(Map0, A1, V, MapF). check(Map0, A1, V, MapF).

View File

@ -15,13 +15,10 @@ add_lib(YAPPython pyload.c ${PYTHON_HEADERS} )
if (WIN32) if (WIN32)
add_library (Py4YAP OBJECT ${PYTHON_SOURCES} ${PYTHON_HEADERS}) add_library (Py4YAP OBJECT ${PYTHON_SOURCES} ${PYTHON_HEADERS})
else() else()
add_corelib(Py4YAP ${PYTHON_SOURCES} ${PYTHON_HEADERS}) add_library(Py4YAP SHARED ${PYTHON_SOURCES} ${PYTHON_HEADERS})
MY_set_target_properties( set_target_properties(
Py4YAP Py4YAP
PROPERTIES VERSION ${YAP_FULL_VERSION} PROPERTIES VERSION ${YAP_FULL_VERSION}
SOVERSION ${YAP_MAJOR_VERSION}.${YAP_MINOR_VERSION} SOVERSION ${YAP_MAJOR_VERSION}.${YAP_MINOR_VERSION}
@ -31,6 +28,20 @@ target_link_libraries(Py4YAP libYap ${PYTHON_LIBRARIES})
# arithmetic hassle. # arithmetic hassle.
install(TARGETS Py4YAP
RUNTIME DESTINATION ${bindir}
LIBRARY DESTINATION ${libdir}
ARCHIVE DESTINATION ${libdir}
)
install(TARGETS YAPPython
LIBRARY DESTINATION ${dlls}
RUNTIME DESTINATION ${dlls}
ARCHIVE DESTINATION ${dlls} )
target_link_libraries( YAPPython Py4YAP ) target_link_libraries( YAPPython Py4YAP )
endif() endif()

View File

@ -81,7 +81,6 @@ static foreign_t python_is(term_t tobj, term_t tf) {
pyErrorAndReturn(rc, false); pyErrorAndReturn(rc, false);
} }
static foreign_t python_proc(term_t tobj) { static foreign_t python_proc(term_t tobj) {
PyObject *o; PyObject *o;
@ -93,7 +92,6 @@ static foreign_t python_proc(term_t tobj) {
pyErrorAndReturn(rc, false); pyErrorAndReturn(rc, false);
} }
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;
@ -215,7 +213,6 @@ term_t stackp = python_acquire_GIL();
pyErrorAndReturn(b, false); pyErrorAndReturn(b, false);
} }
static foreign_t python_builtin_eval(term_t caller, term_t dict, term_t out) { static foreign_t python_builtin_eval(term_t caller, term_t dict, term_t out) {
PyErr_Clear(); PyErr_Clear();
PyObject *pI, *pArgs, *pOut; PyObject *pI, *pArgs, *pOut;
@ -525,7 +522,6 @@ static foreign_t python_export(term_t t, term_t pl) {
pyErrorAndReturn(rc, false); pyErrorAndReturn(rc, false);
} }
/** /**
* @pred python_import(MName, Mod) * @pred python_import(MName, Mod)
* Import a python module to the YAP environment. * Import a python module to the YAP environment.
@ -543,7 +539,7 @@ term_t t0 = python_acquire_GIL();
char s0[MAXPATHLEN], *s = s0; char s0[MAXPATHLEN], *s = s0;
while (true) { while (true) {
size_t len; size_t len;
PyErr_Clear();
len = (MAXPATHLEN - 1) - (s - s0); len = (MAXPATHLEN - 1) - (s - s0);
if (PL_is_pair(mname)) { if (PL_is_pair(mname)) {
char *sa = NULL; char *sa = NULL;

View File

@ -1,12 +1,6 @@
# This is a CMake example for Python # This is a CMake example for Python
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap4py)
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap4py/include)
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog)
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog/os)
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog/pl)
INCLUDE(UseSWIG) INCLUDE(UseSWIG)
include(FindPythonModule) include(FindPythonModule)
@ -16,10 +10,11 @@ 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 yap) SET_SOURCE_FILES_PROPERTIES(../../swiyap.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)
set(YAP4PY_PL prolog/jupyter.yap prolog/yapi.yap)
configure_file("setup.py.in" ${CMAKE_CURRENT_BINARY_DIR}/setup.py) configure_file("setup.py.in" ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
configure_file("MANIFEST.in" ${CMAKE_CURRENT_BINARY_DIR}/MANIFEST.in) configure_file("MANIFEST.in" ${CMAKE_CURRENT_BINARY_DIR}/MANIFEST.in)
@ -32,21 +27,6 @@ INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/i
SWIG_ADD_LIBRARY(Py2YAP LANGUAGE python SHARED SOURCES ../../swig/yap.i )
if (WIN32)
SWIG_LINK_LIBRARIES(Py2YAP YAPPython libYap ${PYTHON_LIBRARIES} )
else()
SWIG_LINK_LIBRARIES( Py2YAP libYap YAP++ YAPPython ${PYTHON_LIBRARIES} )
endif()
set_target_properties ( ${SWIG_MODULE_Py2YAP_REAL_NAME}
PROPERTIES
NO_SONAME ON
OUTPUT_NAME yap
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS YAPPython
)
SET(SWIG_SOURCES SET(SWIG_SOURCES
${CMAKE_SOURCE_DIR}/packages/swig/yap.i ${CMAKE_SOURCE_DIR}/packages/swig/yap.i
@ -64,41 +44,6 @@ else()
add_custom_command( OUTPUT yap.i
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/packages/swig/yap.i .
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${CMAKE_SOURCE_DIR}/packages/swig/yap.i )
add_custom_command( OUTPUT yapi.cpp
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/CXX/yapi.cpp .
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${CMAKE_SOURCE_DIR}/CXX/yapi.cpp )
add_custom_command( OUTPUT yap4py/prolog/lists.yap
COMMAND ${CMAKE_COMMAND} -E copy ${pl_library} yap4py/prolog
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${pl_library} )
add_custom_command( OUTPUT yap4py/prolog/os/yio.yap
COMMAND ${CMAKE_COMMAND} -E copy ${pl_os_library} yap4py/prolog/os
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${pl_os_library} )
add_custom_command( OUTPUT yap4py/prolog/pl/boot.yap
COMMAND ${CMAKE_COMMAND} -E copy ${pl_boot_library} yap4py/prolog/pl
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${pl_boot_library} )
add_custom_command( OUTPUT yap4py/include/YapInterface.h
COMMAND ${CMAKE_COMMAND} -E copy ${c_headers} yap4py/include
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${c_headers} )
add_custom_command( OUTPUT yap4py/include/yapi.hh
COMMAND ${CMAKE_COMMAND} -E copy ${cxx_headers} yap4py/include
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${cxx_headers} )
if (CONDA) if (CONDA)
set(bdist bdist_conda) set(bdist bdist_conda)
else() else()
@ -107,32 +52,25 @@ endif()
add_custom_target( YAP4PY ALL add_custom_target( YAP4PY ALL
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/startup.yss ${CMAKE_CURRENT_BINARY_DIR}/yap4py COMMAND ${CMAKE_COMMAND} -E remove_directory yap4py
COMMAND ${CMAKE_COMMAND} -E copy ${CONFIGURATION_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/include COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/yap4py yap4py
COMMAND ${SWIG_EXECUTABLE} -c++ -python -O -py3 -module "yap" -outcurrentdir -addextern -Iyap4py/include -outdir ${CMAKE_CURRENT_BINARY_DIR} -I${GMP_INCLUDE_DIRS} -DX_API="" -o yapPyTHON_wrap.cxx ${SWIG_SOURCES} COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/CXX/yapi.cpp yap4py
COMMAND ${SWIG_EXECUTABLE} -c++ -python -O -py3 -module "yap" -addextern -I${CMAKE_SOURCE_DIR}/H -I${CMAKE_SOURCE_DIR}/H/generated -I${CMAKE_SOURCE_DIR}/include -I${CMAKE_SOURCE_DIR}/OPTYap -I${CMAKE_SOURCE_DIR}/os -I${CMAKE_SOURCE_DIR}/utf8proc -I.././.. -I${CMAKE_SOURCE_DIR}/CXX -I${CMAKE_SOURCE_DIR}/packages/python -outdir ${CMAKE_CURRENT_BINARY_DIR}/yap4py -I${GMP_INCLUDE_DIRS} -DX_API="" -o yap4py/yap_wrap.cxx -oh yap4py/yap_wrap.hh ${SWIG_SOURCES}
COMMAND ${PYTHON_EXECUTABLE} setup.py sdist ${bdist} COMMAND ${PYTHON_EXECUTABLE} setup.py sdist ${bdist}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${YAP_DLLS} STARTUP yap4py/prolog/pl/boot.yap yapi.cpp yap4py/include/yapi.hh yap4py/include/YapInterface.h yap4py/prolog/os/yio.yap yap4py/prolog/lists.yap yap.i DEPENDS ${SWIG_SOURCES} Py4YAP YAP++
) )
function(f_copy filename output ) install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --ignore-installed .
get_filename_component(base ${filename} NAME_WE)
set(outfile ${output}/${base})
file (COPY ${filename} DESTiNATION ${output})
add_custom_command(
OUTPUT ${outfile}
COMMAND ${CMAKE_COMMAND} -E COPY ${filename} ${outfile}
DEPENDS ${filename}
)
set_source_files_properties(${outfile} PROPERTIES GENERATED TRUE)
endfunction()
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install .
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})" WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})"
DEPENDS Py4YAP ${CMAKE_BINARY_DIR}/${YAP_STARTUP} ${dlls} ) DEPENDS Py4YAP ${CMAKE_BINARY_DIR}/${YAP_STARTUP} ${dlls} )
install(FILES ${YAP4PY_PL} DESTINATION ${libpl} )
add_to_group( YAP4PY_PL pl_library )
if (WITH_DOCS AND DOXYGEN_FOUND) if (WITH_DOCS AND DOXYGEN_FOUND)
set(CMAKE_SWIG_FLAGS -DDOXYGEN=${DOXYGEN_FOUND}) set(CMAKE_SWIG_FLAGS -DDOXYGEN=${DOXYGEN_FOUND})

View File

@ -23,6 +23,8 @@
:- python_import(yap4py.yapi). :- python_import(yap4py.yapi).
%:- start_low_level_trace.
%% @pred yapi_query( + VarList, - Dictionary) %% @pred yapi_query( + VarList, - Dictionary)
%% %%
%% dictionary, Examples %% dictionary, Examples
@ -32,18 +34,25 @@
show_answer(VarNames, Dict), show_answer(VarNames, Dict),
Self.bindings := Dict. Self.bindings := Dict.
:- initialization set_preds.
%:- initialization set_preds.
set_preds :- set_preds :-
current_predicate(P, Q), current_predicate(P, Q),
functor(Q,P,A), functor(Q,P,A),
atom_string(P,S), atom_string(P,S),
catch(
:= yap4py.yapi.named( S, A), := yap4py.yapi.named( S, A),
_,
fail),
fail. fail.
set_preds :- set_preds :-
system_predicate(P/A), system_predicate(P/A),
atom_string(P,S), atom_string(P,S),
catch(
:= yap4py.yapi.named( S, A), := yap4py.yapi.named( S, A),
_,
fail),
fail. fail.
set_preds. set_preds.

View File

@ -65,13 +65,13 @@ if platform.system() == 'Windows':
my_extra_link_args = ['-Wl,-export-all-symbols'] my_extra_link_args = ['-Wl,-export-all-symbols']
else: else:
#if platform.system() == 'Darwin': #if platform.system() == 'Darwin':
my_extra_link_args = ['-Wl,-rpath','-Wl,@loader_path/../../..'] my_extra_link_args = ['-Wl,-rpath','-Wl,@loader_path']
win_libs = [] win_libs = []
local_libs = ['Py4YAP'] local_libs = ['Py4YAP']
# or dll in glob('yap/dlls/*'): # or dll in glob('yap/dlls/*'):
# move( dll ,'lib' ) # move( dll ,'lib' )
native_sources = ["yapPYTHON_wrap.cxx",'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}") #python_libdir = path.abspath(path.dirname("${PYTHON_LIBRARIES}")
@ -79,7 +79,7 @@ native_sources = ["yapPYTHON_wrap.cxx",'yapi.cpp']
extensions = [Extension('_yap', native_sources, extensions = [Extension('yap4py._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'),
@ -91,20 +91,24 @@ extensions = [Extension('_yap', native_sources,
'-DX_API', '-Iyap4py/include' ], '-DX_API', '-Iyap4py/include' ],
library_dirs=[".",'../../..'], library_dirs=[".",'../../..'],
extra_link_args=my_extra_link_args, extra_link_args=my_extra_link_args,
libraries=['Yap','Py4YAP','gmp']+win_libs+local_libs, libraries=['Yap','gmp']+win_libs+local_libs,
include_dirs=['yap4py/include'] include_dirs=['${CMAKE_SOURCE_DIR}/H',
'${CMAKE_SOURCE_DIR}/H/generated',
'${CMAKE_SOURCE_DIR}/include',
'${CMAKE_SOURCE_DIR}/OPTYap',
'${CMAKE_SOURCE_DIR}/os',
'${CMAKE_SOURCE_DIR}/utf8proc',
'${CMAKE_SOURCE_DIR}/packages/python',
'../../..',
'${CMAKE_SOURCE_DIR}/CXX' ]
)] )]
packages = setuptools.find_packages('${CMAKE_CURRENT_SOURCE_DIR}')
package_data = { package_data = {
'yap4py/prolog': 'prolog/*.*', #'': '*.*'
'': '*.*'
} }
data_files=[('../..', glob('lib*.*'))] data_files=[]
version_ns = {'__version__': '6.3.5', 'minor-version': '6', 'minor-version': '3', 'patch': '5'} version_ns = {'__version__': '6.3.5', 'minor-version': '6', 'minor-version': '3', 'patch': '5'}
@ -112,10 +116,10 @@ setup_args = dict(
name=name, name=name,
version=version_ns['__version__'], version=version_ns['__version__'],
scripts=glob(join('scripts', '*')), scripts=glob(join('scripts', '*')),
packages=packages, packages=['yap4py'],
ext_modules=extensions, ext_modules=extensions,
py_modules=['yap','yap4py.yapi'], py_modules=[],
package_data=package_data, # package_data=package_data,
include_package_data=True, include_package_data=True,
data_files = data_files, data_files = data_files,
# requirements=[ # requirements=[

View File

@ -6,8 +6,8 @@ import os.path
import platform import platform
import sys import sys
global yap_lib_path # global yap_lib_path
yap_lib_path = os.path.dirname(__file__) #yap_lib_path = os.path.dirname(__file__)
if platform.system() == 'Windows': if platform.system() == 'Windows':
def load( dll ): def load( dll ):
@ -15,10 +15,10 @@ if platform.system() == 'Windows':
dll = os.path.abspath(dll) dll = os.path.abspath(dll)
ctypes.WinDLL(dll) ctypes.WinDLL(dll)
load('libYap*') load('libYap*')
else: # else:
def load( dll ): # def load( dll ):
dll = glob.glob(os.path.join(yap_lib_path,dll))[0] # dll = glob.glob(os.path.join(yap_lib_path,dll))[0]
dll = os.path.abspath(dll) # dll = os.path.abspath(dll)
ctypes.CDLL(dll, mode=ctypes.RTLD_GLOBAL) # ctypes.CDLL(dll, mode=ctypes.RTLD_GLOBAL)
# load('libYap*') # load('libYap*')
# load('libPy4YAP*') # load('libPy4YAP*')

View File

@ -6,14 +6,16 @@ import keyword
# import pdb # import pdb
from collections import namedtuple from collections import namedtuple
from yap import * from .yap import *
class Engine( YAPEngine ): class Engine( YAPEngine ):
def __init__(self, args=None,**kwargs): def __init__(self, args=None,**kwargs):
# type: (object) -> object # type: (object) -> object
self.contained = False
if not args: if not args:
args = EngineArgs(**kwargs) args = EngineArgs(**kwargs)
if self.contained:
yap_lib_path = os.path.dirname(__file__) yap_lib_path = os.path.dirname(__file__)
args.setYapShareDir(os.path.join(yap_lib_path,"prolog")) args.setYapShareDir(os.path.join(yap_lib_path,"prolog"))
args.setYapLibDir(yap_lib_path) args.setYapLibDir(yap_lib_path)
@ -84,19 +86,10 @@ class PrologTableIter:
self.q = None self.q = None
raise StopIteration() raise StopIteration()
f2p = [] f2p = {"fails":{}}
for i in range(16): for i in range(16):
f2p += [{}] f2p[i] ={}
def named( name, arity):
if arity > 0 and name.isidentifier() and not keyword.iskeyword(name):
s = []
for i in range(arity):
s += ["A" + str(i)]
f2p[arity][name] = namedtuple(name, s)
class PrologPredicate( YAPPrologPredicate ):
""" Interface to Prolog Predicate"""
@ -115,6 +108,20 @@ yapi_query = namedtuple( 'yapi_query', 'vars dict')
show_answer = namedtuple( 'show_answer', 'vars dict') show_answer = namedtuple( 'show_answer', 'vars dict')
set_prolog_flag = namedtuple('set_prolog_flag', 'flag new_value') set_prolog_flag = namedtuple('set_prolog_flag', 'flag new_value')
def named( name, arity):
try:
if arity > 0 and name.isidentifier() and not keyword.iskeyword(name):
s = []
for i in range(arity):
s += ["A" + str(i)]
f2p[arity][name] = namedtuple(name, s)
except:
f2p[fails][name] = True
class PrologPredicate( YAPPrologPredicate ):
""" Interface to Prolog Predicate"""
class v(YAPVarTerm): class v(YAPVarTerm):
def __init__(self): def __init__(self):
super().__init__() super().__init__()