python support

This commit is contained in:
Vitor Santos Costa
2017-05-27 22:54:00 +01:00
parent 25a2b68b15
commit 0c46c894d3
46 changed files with 273711 additions and 118760 deletions

View File

@@ -32,8 +32,8 @@ IF(WIN32)
ARCHIVE DESTINATION ${libdir} )
else()
install(TARGETS YAPPython
LIBRARY DESTINATION ${libdir}
RUNTIME DESTINATION ${libdir}
ARCHIVE DESTINATION ${libdir} )
LIBRARY DESTINATION ${dlls}
RUNTIME DESTINATION ${dlls}
ARCHIVE DESTINATION ${dlls} )
endif()

View File

@@ -18,6 +18,51 @@ void YEM(const char *exp, int line, const char *file, const char *code)
fprintf(stderr, "**** Warning,%s@%s:%d: failed while executing %s\n", code, file, line, exp);
}
static PyObject *s_to_python( const char *s, bool eval, PyObject *p0)
{
PyObject *o;
if (eval)
{
o = PythonLookup(s,p0);
/* if (!o)
return o;
*/
}
else
{
o = PythonLookupSpecial(s);
}
if (o)
{
Py_INCREF(o);
return CHECKNULL(YAP_MkStringTerm(s), o);
} else {
PyObject *pobj = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
return pobj;
}
}
/**
* obtain the object matching a certain string.
*
* @param t handle to Prolog term
* @param t whether should try to evaluate evaluables.
*
* @return a Python object descriptor or NULL if failed
*/
X_API PyObject *string_to_python( const char *s, bool eval, PyObject *p0)
{
char *buf = malloc(strlen(s)+1), *child;
while((child = strchr(s,'.')) != NULL ) {
size_t len = child - s;
strncpy(buf,s,len);
buf[len]='\0';
p0 = s_to_python(buf, eval, p0);
s = child+1;
}
return s_to_python(s, eval, p0);
}
/**
* term_to_python translates and evaluates from Prolog to Python
*

View File

@@ -15,7 +15,7 @@
static PyObject *finalLookup(PyObject *i, const char *s) {
PyObject *rc;
if (i == NULL)
return Py_None;
return NULL;
if (strcmp(s,"none") == 0)
return Py_None;
if (PyDict_Check(i)) {
@@ -34,7 +34,7 @@ static PyObject *finalLookup(PyObject *i, const char *s) {
PyObject *PythonLookupSpecial(const char *s) {
if (s == NULL)
return Py_None;
return NULL;
if (strcmp(s, "true") == 0) {
return Py_True;
}
@@ -52,9 +52,9 @@ PyObject *PythonLookupSpecial(const char *s) {
}
PyObject *lookupPySymbol(const char *sp, PyObject *pContext, PyObject **duc) {
PyObject *out = Py_None;
PyObject *out = NULL;
if (!sp)
return Py_None;
return NULL;
if ((out = finalLookup(pContext, sp))) {
return out;
}
@@ -66,54 +66,32 @@ PyObject *lookupPySymbol(const char *sp, PyObject *pContext, PyObject **duc) {
return out;
}
PyObject *py_Local = PyEval_GetLocals();
if ((out = finalLookup(py_Local, sp))) {
if ((out = finalLookup(py_Local, sp)) && out != Py_None) {
return out;
}
PyObject *py_Global = PyEval_GetGlobals();
if ((out = finalLookup(py_Global, sp))) {
if ((out = finalLookup(py_Global, sp)) ) {
return out;
}
if ((out = finalLookup(py_ModDict, sp))) {
return out;
}
if ((out = finalLookup(py_Main, sp))) {
if ((out = finalLookup(py_Main, sp)) ) {
return out;
}
return Py_None;
}
int lookupPyModule(Py_mod *q) {
char buf[1024], *S = buf;
int prefix = 0;
int j;
py_ModDict = PyObject_GetAttrString(py_Sys, "modules");
PyObject *ob;
S[0] = '\0';
while (YAP_IsAtomTerm(q->names[prefix])) {
strcat(S, YAP_AtomName(YAP_AtomOfTerm(q->names[prefix])));
strcat(S, ".");
S += strlen(S);
prefix++;
}
for (j = prefix; j > 0; j--) {
S = strrchr(buf, '.');
S[0] = '\0';
if ((ob = PyDict_GetItemString(py_ModDict, buf)) != NULL &&
PyModule_Check(ob)) {
Py_INCREF(ob);
q->mod = ob;
return j;
}
}
return 0;
return NULL;
}
PyObject *PythonLookup(const char *s, PyObject *oo) {
PyObject *o;
if ((o = PythonLookupSpecial(s)))
return o;
return lookupPySymbol(s, oo, NULL);
if ((o = lookupPySymbol(s, oo, NULL)) == NULL)
return NULL;
else {
Py_INCREF(o);
return o;
}
}
PyObject *find_obj(PyObject *ob, term_t l, bool eval) {

View File

@@ -629,16 +629,15 @@ PyThreadState *tstate;
static YAP_Int p_python_threaded(void) {
PyErr_Clear();
PyRun_SimpleString("print( \"thread initiated\" )");
// PyEval_ReleaseThread(tstate);
_threaded = true;
// _threaded = true;
// _locked = 0;
pyErrorAndReturn(true, false);
}
static PyGILState_STATE gstate;
term_t python_acquire_GIL(void) {
term_t python_acquire_GIL(void) {
term_t curSlot = 1; //PL_new_term_ref();
if (!_threaded)
pyErrorAndReturn(curSlot, false);

View File

@@ -1,5 +1,7 @@
#include "python.h"
#include <YapStreams.h>
#include <VFS.h>
atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
ATOM_comma, ATOM_builtin, ATOM_A, ATOM_V, ATOM_self, ATOM_nil, ATOM_brackets, ATOM_curly_brackets;
@@ -19,6 +21,88 @@ X_API PyObject *py_Sys;
PyObject *py_Context;
PyObject *py_ModDict;
VFS_t pystream;
static void *
py_open( const char *name, const char *io_mode) {
if (strcasestr(name,"//python/")== name)
name += strlen("//python/");
// we assume object is already open, so there is no need to open it.
PyObject *stream = string_to_python( name, true, NULL);
if (stream == Py_None)
return NULL;
return stream;
}
static bool
py_close(int sno) {
PyObject *s = YAP_foreign_stream(sno);
PyObject* fclose = PyObject_GetAttrString(s, "close");
PyObject* rc= PyObject_CallObject(fclose, NULL);
bool v = (rc == Py_True);
return v;
}
static PyObject * pyw; // buffer
static int pyw_kind;
PyObject * pyw_data;
static int
py_put(int sno, int ch) {
PyObject *s = YAP_foreign_stream(sno);
PyUnicode_WRITE( pyw_kind, pyw_data, 0, ch );
PyObject* fput = PyObject_GetAttrString(s, "write");
PyObject_CallFunctionObjArgs(fput, pyw, NULL);
return ch;
}
static int
py_get(int sno) {
PyObject *s = YAP_foreign_stream(sno);
PyObject* fget = PyObject_GetAttrString(s, "read");
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) {
PyObject *s = YAP_foreign_stream(sno);
PyObject* fseek = PyObject_GetAttrString(s, "seek");
PyObject *pyr = PyObject_CallFunctionObjArgs(fseek, PyLong_FromLong(where), PyLong_FromLong(how), NULL);
return PyLong_AsLong(pyr);
}
static void
py_flush(int sno) {
PyObject *s = YAP_foreign_stream(sno);
PyObject* flush = PyObject_GetAttrString(s, "flush");
PyObject_CallFunction( flush, NULL);
}
static bool
init_python_stream(void)
{
pyw = PyUnicode_FromString("x");
pyw_kind = PyUnicode_KIND(pyw);
pyw_data = PyUnicode_DATA(pyw);
pystream.name = "python stream";
pystream.vflags = VFS_CAN_WRITE|VFS_CAN_EXEC| VFS_CAN_SEEK|VFS_HAS_PREFIX;
pystream.prefix = "//python/";
pystream.suffix = NULL;
pystream.open = py_open;
pystream.close = py_close;
pystream.get_char = py_get;
pystream.put_char = py_put;
pystream.flush = py_flush;
pystream.seek = py_seek;
pystream.next = GLOBAL_VFS;
GLOBAL_VFS = &pystream;
// NULL;
return true;
}
X_API PyObject *py_F2P;
bool python_in_python;
@@ -38,8 +122,10 @@ static void add_modules(void) {
Py_INCREF(py_Yapex);
//py_F2P = PyObject_GetAttrString(py_Yap, "globals");
py_F2P = NULL;
init_python_stream();
}
static void install_py_constants(void) {
FUNCTOR_dot2 = PL_new_functor(PL_new_atom("."), 2);
// FUNCTOR_equal2 = PL_new_functor(PL_new_atom("="), 2);

View File

@@ -44,7 +44,7 @@ typedef struct s_mod_t {
extern X_API YAP_Term pythonToYAP(PyObject *pVal);
extern X_API PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o);
extern X_API PyObject *string_to_python( const char *s, bool eval, PyObject *p0);
typedef YAP_Arity arity_t;
extern atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
@@ -175,7 +175,6 @@ extern bool python_asign(term_t t, PyObject *exp, PyObject *context);
extern foreign_t python_builtin(term_t out);
extern int lookupPyModule(Py_mod *q);
extern PyObject *lookupPySymbol(const char *s, PyObject *q, PyObject **d);
extern install_t install_pypreds(void);

View File

@@ -109,7 +109,6 @@ Data types are
*************************************************************************************************************/
:- use_module(library(shlib)).
:- use_module(library(lists)).
:- use_module(library(apply_macros)).
:- use_module(library(charsio)).
@@ -153,5 +152,3 @@ add_cwd_to_python :-
% done
:- initialization( load_foreign_files([libYAPPython], [], init_python), now ).
:- initialization( load_foreign_library(foreign(libYAPPython), init_python), now ).

View File

@@ -72,13 +72,17 @@ add_custom_target( YAP4PY ALL
COMMAND ${CMAKE_COMMAND} -E copy ${pl_os_library} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog/os
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/setup.py sdist bdist_wheel
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS STARTUP ${dlls} ${PYTHON_SOURCES} ${PROLOG_SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/setup.py ${SWIG_MODULE_Py2YAP_REAL_NAME} )
DEPENDS STARTUP ${dlls} ${PYTHON_SOURCES} ${PROLOG_SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/setup.py ${SWIG_MODULE_Py2YAP_REAL_NAME} )
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --no-index -f dist yap4py
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --force --no-index -f dist yap4py
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})"
DEPENDS Py4YAP ${CMAKE_BINARY_DIR}/${YAP_STARTUP} ${dlls} )
install(FILES yapi.yap DESTINATION ${libpl})
if (WITH_DOCS AND DOXYGEN_FOUND)

View File

@@ -1,13 +1,26 @@
%% @file yapi.yap
%% @brief support yap shell
%%
:- module(yapi, [query/3]).
:- module(yapi, [python_query/2,
python_ouput/0,
yap_query/3]).
:- use_module( library(lists) ).
:- use_module( library(maplist) ).
:- use_module( library(rbtrees) ).
%% @pred yap_query(0:Goal, + VarList, +OutStream, - Dictionary)
%% @pred yap_query(0:Goal, + VarList, - Dictionary)
%%
%% dictionary, Examples
%%
%%
python_query( Engine, String ) :-
atomic_to_term( String, Goal, VarNames ), writeln(Goal),
yap_query( Goal, VarNames, user_error, Dict), writeln(Dict),
Engine.bindings := Dict.
%% @pred yap_query(0:Goal, + VarList, +OutStream, - Dictionary)
%% @pred yap_query(0:Goal, + VarList, - Dictionary)
%%
@@ -24,8 +37,10 @@ yap_query( Goal, VarNames, Stream, Dictionary) :-
prolog:yap_query( Goal, VarNames, Dictionary) :-
yap_query( Goal, VarNames, user_output, Dictionary).
constraints(QVs, Goal, Stream, {Dict}) :-
constraints(QVs0, Goal0, Stream, {Dict}) :-
!,
copy_term(Goal0+QVs0, Goal+QVs),
writeln(ivs-IVs),
term_variables(Goal, IVs),
foldl(enumerate, IVs, 0, _Ns),
out(QVs, Stream, Dict).
@@ -43,7 +58,8 @@ enumerate('$VAR'(A), I, I1) :-
enum(I, [C]) :-
I < 26,
!, C is "A" + I.
!,
C is "A" + I.
enum(I, [C|Cs]) :-
J is I//26,
K is I mod 26,
@@ -63,14 +79,24 @@ v2py(v(I0) = v(I0), I0, I) :-
I is I0+1.
output([V=B], S) :-
format(S, 'a = ~q~n', [V, B]).
!,
format(S, '~a = ~q~n', [V, B]).
output([V=B|Ns], S) :-
format( S, 'a = ~q.~n', [V, B]),
format( S, '~a = ~q.~n', [V, B]),
output( Ns, S).
bvs([V=B],{V:B}) :-
!.
bvs([V=B|Ns], (V:B,N)) :-
output( Ns, N).
:- start_low_level_trace.
bvs([V=B], S:B) :-
atring_to_atom(V,S),
!.
bvs([V=B|Ns], (S:B,N) ) :-
atring_to_atom(V,S),
output( Ns, N).
python_output :-
:= import(sys),
open('//python/sys.stdout', append, Output),
open('//python/sys.stderr', append, Error),
set_prolog_flag(user_output, Output),
set_prolog_flag(user_error, Error).

View File

@@ -1,78 +1,72 @@
set (EXTRAS
MANIFEST.in
YAP_KERNEL.md
)
set (EXTRAS
MANIFEST.in
YAP_KERNEL.md
)
set (PYTHON_SOURCES
yap_kernel_launcher.py
data_kernelspec/kernel.json
yap_kernel/__init__.py
yap_kernel/__main__.py
yap_kernel/_version.py
yap_kernel/codeutil.py
yap_kernel/connect.py
yap_kernel/datapub.py
yap_kernel/displayhook.py
yap_kernel/embed.py
yap_kernel/eventloops.py
yap_kernel/heartbeat.py
yap_kernel/interactiveshell.py
yap_kernel/iostream.py
yap_kernel/jsonutil.py
yap_kernel/kernelapp.py
yap_kernel/kernelbase.py
yap_kernel/kernelspec.py
yap_kernel/log.py
yap_kernel/parentpoller.py
yap_kernel/pickleutil.py
yap_kernel/serialize.py
yap_kernel/yapkernel.py
yap_kernel/zmqshell.py
yap_kernel/comm/__init__.py
yap_kernel/comm/comm.py
yap_kernel/comm/manager.py
yap_kernel/gui/__init__.py
yap_kernel/gui/gtk3embed.py
yap_kernel/gui/gtkembed.py
yap_kernel/inprocess/__init__.py
yap_kernel/inprocess/blocking.py
yap_kernel/inprocess/channels.py
yap_kernel/inprocess/client.py
yap_kernel/inprocess/constants.py
yap_kernel/inprocess/ipkernel.py
yap_kernel/inprocess/manager.py
yap_kernel/inprocess/socket.py
yap_kernel/pylab/__init__.py
yap_kernel/pylab/backend_inline.py
yap_kernel/pylab/config.py
)
set (PYTHON_SOURCES
yap_kernel_launcher.py
data_kernelspec/kernel.json
yap_kernel/__init__.py
yap_kernel/__main__.py
yap_kernel/_version.py
yap_kernel/codeutil.py
yap_kernel/connect.py
yap_kernel/datapub.py
yap_kernel/displayhook.py
yap_kernel/embed.py
yap_kernel/eventloops.py
yap_kernel/heartbeat.py
yap_kernel/interactiveshell.py
yap_kernel/iostream.py
yap_kernel/jsonutil.py
yap_kernel/kernelapp.py
yap_kernel/kernelbase.py
yap_kernel/kernelspec.py
yap_kernel/log.py
yap_kernel/parentpoller.py
yap_kernel/pickleutil.py
yap_kernel/serialize.py
yap_kernel/yapkernel.py
yap_kernel/zmqshell.py
yap_kernel/comm/__init__.py
yap_kernel/comm/comm.py
yap_kernel/comm/manager.py
yap_kernel/gui/__init__.py
yap_kernel/gui/gtk3embed.py
yap_kernel/gui/gtkembed.py
yap_kernel/inprocess/__init__.py
yap_kernel/inprocess/blocking.py
yap_kernel/inprocess/channels.py
yap_kernel/inprocess/client.py
yap_kernel/inprocess/ipkernel.py
yap_kernel/inprocess/manager.py
yap_kernel/inprocess/socket.py
yap_kernel/pylab/__init__.py
yap_kernel/pylab/backend_inline.py
yap_kernel/pylab/config.py
)
foreach(i ${PYTHON_SOURCES})
configure_file(${i} ${CMAKE_CURRENT_BINARY_DIR}/${i})
endforeach()
configure_file("setup.py" ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
configure_file("MANIFEST.in" ${CMAKE_CURRENT_BINARY_DIR}/MANIFEST.in)
configure_file("YAP_KERNEL.md" ${CMAKE_CURRENT_BINARY_DIR}/README)
configure_file("yap_kernel/_version.py" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/_version.py )
configure_file("${CMAKE_SOURCE_DIR}/docs/icons/yap_32x32x32.png" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png)
configure_file("${CMAKE_SOURCE_DIR}/docs/icons/yap_64x64x32.png" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-64x64.png)
configure_file("${CMAKE_SOURCE_DIR}/misc/editors/prolog.js" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/prolog.js)
configure_file(setup.py.in ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources)
file(COPY yap_kernel DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
file( COPY MANIFEST.in setup.cfg data_kernelspec yap_kernel_launcher.py DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
# file( GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/README.md INPUT YAP_KERNEL.md )
file( COPY yap_kernel/_version.py DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel )
file( GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png INPUT ${CMAKE_SOURCE_DIR}/docs/icons/yap_32x32x32.png )
file( GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-64x64.png INPUT ${CMAKE_SOURCE_DIR}/docs/icons/yap_64x64x32.png )
file( COPY ${CMAKE_SOURCE_DIR}/misc/editors/prolog.js DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/)
set(SETUP_PY "${CMAKE_CURRENT_BINARY_DIR}/setup.py")
set( PYTHON_INSTALL sdist bdist_wheel)
set(SETUP_PY ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
add_custom_target( YAPKernel ALL
add_custom_target( YAPKernel ALL
COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} sdist
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
)
COMMAND ${PYTHON_EXECUTABLE} setup.py clean sdist bdist_wheel
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS libYap ${SWIG_MODULE_Py2YAP_REAL_NAME}
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --no-index -f dist yap_kernel
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})")
)
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --no-index -f dist yap_kernel")
install(FILES jupyter.yap
DESTINATION ${libpl}
)
# install(FILES jupyter.yap
# DESTINATION ${libpl} )

View File

@@ -14,10 +14,11 @@ name = 'yap_kernel'
#-----------------------------------------------------------------------------
import sys
import setuptools
v = sys.version_info
if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)):
error = "ERROR: %s requires Python version 2.7 or 3.3 or above." % name
error = "ERROR: %s requires Python version 3.3 or above." % name
print(error, file=sys.stderr)
sys.exit(1)
@@ -34,23 +35,26 @@ import shutil
from distutils.core import setup
pjoin = os.path.join
here = os.path.relpath(os.path.dirname(__file__))
pkg_root = pjoin(here, name)
here = os.path.abspath(os.path.dirname(__file__))
# pkg_root = pjoin(here, name)
packages = []
for d, _, _ in os.walk(pjoin(here, name)):
if os.path.exists(pjoin(d, '__init__.py')):
packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
packages = setuptools.find_packages('${CMAKE_CURRENT_SOURCE_DIR}')
# for d, _, _ in os.walk(pjoin(here, name)):
# if os.path.exists(pjoin(d, '__init__.py')):
# packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
package_data = {
'ipykernel': ['resources/*.*'],
'yap_kernel': ['resources/*.*'],
}
version_ns = {}
with open(pjoin(here, name, '_version.py')) as f:
with open(pjoin('${CMAKE_CURRENT_SOURCE_DIR}', name, '_version.py')) as f:
exec(f.read(), {}, version_ns)
setup_args = dict(
name = name,
version = version_ns['__version__'],
@@ -59,8 +63,8 @@ setup_args = dict(
py_modules = ['yap_kernel_launcher'],
package_data = package_data,
description = "YAP Kernel for Jupyter",
author = 'IPython Development Team and Vitor Santos Costa',
author_email = 'vsc@dcc.fc.up.ot',
author = 'YP Development Team',
author_email = 'YAP-dev@scipy.org',
url = 'http://ipython.org',
license = 'BSD',
platforms = "Linux, Mac OS X, Windows",
@@ -70,8 +74,8 @@ setup_args = dict(
'Intended Audience :: System Administrators',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Prolog',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
)
@@ -85,7 +89,6 @@ install_requires = setuptools_args['install_requires'] = [
'traitlets>=4.1.0',
'jupyter_client',
'tornado>=4.0',
'yap4py'
]
if any(a.startswith(('bdist', 'build', 'install')) for a in sys.argv):
@@ -101,10 +104,6 @@ if any(a.startswith(('bdist', 'build', 'install')) for a in sys.argv):
(pjoin('share', 'jupyter', 'kernels', KERNEL_NAME), glob(pjoin(dest, '*'))),
]
setuptools_args['zip_safe']=False
setuptools_args['eager_resources'] = ['yap_kernel']
setuptools_args['include_package_data']=True
extras_require = setuptools_args['extras_require'] = {
'test:python_version=="2.7"': ['mock'],
'test': ['nose_warnings_filters', 'nose-timer'],

View File

@@ -1,3 +1,4 @@
"""An in-process kernel"""
# Copyright (c) IPython Development Team.

View File

@@ -73,7 +73,6 @@ from IPython.utils.io import ask_yes_no
from IPython.utils.ipstruct import Struct
from IPython.paths import get_ipython_dir
from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
from IPython.utils.process import system, getoutput
from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
with_metaclass, iteritems)
from IPython.utils.strdispatch import StrDispatch
@@ -93,7 +92,8 @@ bindvars = namedtuple('bindvars', 'list')
library = namedtuple('library', 'list')
v = namedtuple('_', 'slot')
load_files = namedtuple('load_files', 'file ofile args')
python_query = namedtuple('python_query', 'query_mgr string')
python_output = namedtuple('python_output', 'oldOut oldErryapi')
class YAPInteraction:
"""An enhanced, interactive shell for YAP."""
@@ -114,9 +114,11 @@ class YAPInteraction:
# args.setYapPrologBootFile(os.path.join(yap_lib_path."startup.yss"))
self.yapeng = yap.YAPEngine(self.args)
self.q = None
self.yapeng.goal(use_module(library('yapi')))
self.shell = shell
self.run = False
self.yapeng.goal(use_module(library('python')))
self.yapeng.goal(use_module(library('yapi')))
self.yapeng.goal(python_output(OldOi ))
def eng(self):
return self.yapeng
@@ -126,9 +128,41 @@ class YAPInteraction:
self.q.close()
self.q = None
def numbervars(self, l):
return self.yapeng.fun(bindvars(l))
def more(self):
if self.q.next():
if self.q.deterministic():
# done
self.q.close()
self.q = None
return True
self.q.close()
self.q = None
return False
def query_prolog(self, s):
if self.q:
return self.restart(s)
if not s:
return True
self.q = self.yapeng.qt(python_query(self,s))
# for eq in vs:
# if not isinstance(eq[0],str):
# print( "Error: Variable Name matches a Python Symbol")
# return False
return self.more()
def restart(self, s):
if s.startswith(';') or s.startswith('y'):
return self.more()
elif s.startswith('#'):
exec(s.lstrip('#'))
elif s.startswith('*'):
while self.more():
pass
print("No (more) answers")
self.q.close()
self.q = None
return False
def run_cell(self, s, store_history=True, silent=False,
@@ -160,63 +194,48 @@ class YAPInteraction:
result : :class:`ExecutionResult`
"""
# construct a query from a one-line string
# q is opaque to Python
# vs is the list of variables
# you can print it out, the left-side is the variable name,
# the right side wraps a handle to a variable
# pdb.set_trace()
# #pdb.set_trace()
# atom match either symbols, or if no symbol exists, strings, In this case
# variable names should match strings
# ask = True
# launch the query
result = ExecutionResult()
result.execution_count = self.shell.execution_count
def error_before_exec(value):
result.error_before_exec = value
self.shell.last_execution_succeeded = False
if not s or s.isspace():
self.shell.last_execution_succeeded = True
return result
# inspect for ?? in the text
# print(st)
#
maxits = 2
if store_history:
result.execution_count = self.shell.execution_count
s = s.strip('\n\j\r\t ')
if not self.q or s:
(self.q,out) = self.top_level(s, out)
else:
out = q.next_answer()
if self.q:
st = s.strip('\n\j\r\t ')
if st and st == '*':
maxits = 1
elif st and st.isdigit():
maxits = int(st)*2
elif st and st != ';':
self.closeq()
if not self.q:
try:
if s:
self.q = self.yapeng.query(ya[q.__hash__])
self.vs = self.q.namedVarsVector()
else:
return
except SyntaxError:
return error_before_exec(sys.exc_info()[1])
cell = s # cell has to exist so it can be stored/logged
# Store raw and processed history
# if not silent:
# self.shell..logger.log(cell, s)
has_raised = False
try:
while (maxits != 0):
self.do_loop(maxits, gs)
except Exception:
result.error_in_exec = sys.exc_info()[1]
has_raised = True
self.closeq()
self.query_prolog(s)
self.shell.last_execution_succeeded = True
result.result = True
except Exception as e:
print(e)
self.shell.last_execution_succeeded = False
result.result = False
self.shell.last_execution_succeeded = not has_raised
result.result = self.shell.last_execution_succeeded
# Reset this so later displayed values do not modify the
# ExecutionResult
# self.displayhook.exec_result = None
# self.events.trigger('post_execute')
# if not silent:
# self.events.trigger('post_self.run_cell')
#self.events.trigger('post_execute')
#if not silent:
# self.events.trigger('post_run_cell')
if store_history:
# Write output to the database. Does nothing unless
# history output logging is enabled.
# self.history_manager.store_output(self.execution_count)
# Each cell is a *single* input, regardless of how many lines it has
self.shell.execution_count += 1
return result

View File

@@ -12,6 +12,7 @@ from traitlets import Instance, Type, Any, List
from .comm import CommManager
from .kernelbase import Kernel as KernelBase
from .zmqshell import ZMQInteractiveShell
from .interactiveshell import YAPInteraction
class YAPKernel(KernelBase):
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',