extensions
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
|
||||
#CHECK: PythonLibs, changed to work in WIN32
|
||||
|
||||
set (PYTHON_SOURCES python.c pl2py.c pybips.c py2pl.c pl2pl.c pypreds.c)
|
||||
set (PYTHON_SOURCES python.c pl2py.c pybips.c py2pl.c pl2pl.c pypreds.c pyio.c)
|
||||
set (PYTHON_HEADERS py4yap.h)
|
||||
set (CMAKE_POSITION_INDEPENDENT_CODE TRUE)
|
||||
|
||||
|
@@ -56,8 +56,10 @@ extern X_API PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o,
|
||||
bool cvt);
|
||||
extern X_API PyObject *string_to_python(const char *s, bool eval, PyObject *p0);
|
||||
typedef YAP_Arity arity_t;
|
||||
extern bool init_python_vfs(void);
|
||||
|
||||
extern atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
|
||||
|
||||
extern atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
|
||||
ATOM_comma, ATOM_builtin, ATOM_V, ATOM_A, ATOM_self, ATOM_nil,
|
||||
ATOM_brackets, ATOM_curly_brackets;
|
||||
|
||||
|
122
packages/python/pyio.c
Normal file
122
packages/python/pyio.c
Normal file
@@ -0,0 +1,122 @@
|
||||
|
||||
|
||||
#include "py4yap.h"
|
||||
#include <VFS.h>
|
||||
|
||||
#include "YapStreams.h"
|
||||
|
||||
VFS_t pystream;
|
||||
|
||||
static void *py_open(VFS_t *me, int sno, const char *name,
|
||||
const char *io_mode) {
|
||||
#if HAVE_STRCASESTR
|
||||
if (strcasestr(name, "/python/") == name)
|
||||
name += strlen("/python/");
|
||||
#else
|
||||
if (strstr(name, "/python/") == name)
|
||||
name += strlen("/python/");
|
||||
#endif
|
||||
StreamDesc *st = YAP_RepStreamFromId(sno);
|
||||
// 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;
|
||||
Py_INCREF(stream);
|
||||
st->u.private_data = stream;
|
||||
st->vfs = me;
|
||||
st->name = YAP_LookupAtom(name);
|
||||
st->user_name = YAP_MkAtomTerm(st->name);
|
||||
return stream;
|
||||
}
|
||||
|
||||
static bool py_close(int sno) { return true; }
|
||||
|
||||
static int py_put(int sno, int ch) {
|
||||
// PyObject *pyw; // buffer
|
||||
// int pyw_kind;
|
||||
// PyObject *pyw_data;
|
||||
// PySys_WriteStdout("%C", ch);
|
||||
// return ch;
|
||||
char s[2];
|
||||
StreamDesc *st = YAP_GetStreamFromId(sno);
|
||||
// PyUnicode_WRITE(pyw_kind, pyw_data, 0, ch);
|
||||
PyObject *err, *fput = PyObject_GetAttrString(st->u.private_data, "write");
|
||||
s[0] = ch;
|
||||
s[1] = '\0';
|
||||
PyObject_CallMethodObjArgs(st->u.private_data, PyUnicode_FromString("write"),
|
||||
PyUnicode_FromString(s), NULL);
|
||||
if ((err = PyErr_Occurred())) {
|
||||
PyErr_SetString(
|
||||
err,
|
||||
"Error in put\n"); // %s:%s:%d!\n", __FILE__, __FUNCTION__, __LINE__);
|
||||
}
|
||||
return ch;
|
||||
}
|
||||
|
||||
static int py_get(int sno) {
|
||||
StreamDesc *s = YAP_GetStreamFromId(sno);
|
||||
PyObject *fget = PyObject_GetAttrString(s->u.private_data, "read");
|
||||
PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL);
|
||||
return PyUnicode_READ_CHAR(pyr, 0);
|
||||
}
|
||||
|
||||
static int py_peek(int sno) {
|
||||
StreamDesc *s = YAP_GetStreamFromId(sno);
|
||||
PyObject *fget = PyObject_GetAttrString(s->u.private_data, "peek");
|
||||
PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL);
|
||||
return PyUnicode_READ_CHAR(pyr, 0);
|
||||
}
|
||||
|
||||
static int64_t py_seek(int sno, int64_t where, int how) {
|
||||
StreamDesc *s = YAP_GetStreamFromId(sno);
|
||||
PyObject *fseek = PyObject_GetAttrString(s->u.private_data, "seek");
|
||||
PyObject *pyr = PyObject_CallFunctionObjArgs(fseek, PyLong_FromLong(where),
|
||||
PyLong_FromLong(how), NULL);
|
||||
return PyLong_AsLong(pyr);
|
||||
}
|
||||
|
||||
static void py_flush(int sno) {
|
||||
StreamDesc *s = YAP_GetStreamFromId(sno);
|
||||
PyObject *flush = PyObject_GetAttrString(s->u.private_data, "flush");
|
||||
PyObject_CallFunction(flush, NULL);
|
||||
}
|
||||
|
||||
#if 0
|
||||
static void python_output(void) {
|
||||
PyObject *stream = string_to_python("sys.stdout", true, NULL);
|
||||
StreamDesc *st = YAP_GetStreamFromId(1);
|
||||
st->u.private_data = stream;
|
||||
st->vfs = &pystream;
|
||||
stream = string_to_python("sys.stderr", true, NULL);
|
||||
st = YAP_GetStreamFromIds(2);
|
||||
st->u.private_data = stream;
|
||||
st->vfs = &pystream;
|
||||
}
|
||||
#endif
|
||||
|
||||
static bool initialized = false;
|
||||
|
||||
bool init_python_vfs(void) {
|
||||
// pyw = PyUnicode_FromString("x");
|
||||
// pyw_kind = PyUnicode_KIND(pyw);
|
||||
// pyw_data = PyUnicode_DATA(pyw);
|
||||
if (initialized)
|
||||
return false;
|
||||
initialized = true;
|
||||
pystream.name = "python stream";
|
||||
pystream.vflags =
|
||||
VFS_CAN_WRITE | VFS_CAN_EXEC | VFS_CAN_READ | VFS_HAS_PREFIX;
|
||||
pystream.prefix = "/python/";
|
||||
pystream.suffix = NULL;
|
||||
pystream.open = py_open;
|
||||
pystream.close = py_close;
|
||||
pystream.get_char = py_get;
|
||||
pystream.peek_char = py_peek;
|
||||
pystream.put_char = py_put;
|
||||
pystream.flush = py_flush;
|
||||
pystream.seek = py_seek;
|
||||
pystream.next = GLOBAL_VFS;
|
||||
GLOBAL_VFS = &pystream;
|
||||
// NULL;
|
||||
return true;
|
||||
}
|
@@ -680,4 +680,6 @@ install_t install_pypreds(void) {
|
||||
PL_register_foreign("python_import", 2, python_import, 0);
|
||||
PL_register_foreign("python_access", 3, python_access, 0);
|
||||
PL_register_foreign("python_threaded", 0, p_python_threaded, 0);
|
||||
|
||||
init_python_vfs();
|
||||
}
|
||||
|
@@ -25,130 +25,6 @@ X_API PyObject *py_Sys;
|
||||
PyObject *py_Context;
|
||||
PyObject *py_ModDict;
|
||||
|
||||
VFS_t pystream;
|
||||
|
||||
static void *
|
||||
py_open(VFS_t *me, int sno, const char *name,
|
||||
const char *io_mode) {
|
||||
#if HAVE_STRCASESTR
|
||||
if (strcasestr(name, "/python/") == name)
|
||||
name += strlen("/python/");
|
||||
#else
|
||||
if (strstr(name, "/python/") == name)
|
||||
name += strlen("/python/");
|
||||
#endif
|
||||
StreamDesc *st = YAP_RepStreamFromId(sno);
|
||||
fprintf(stderr,"opened %d\n", sno);
|
||||
// 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;
|
||||
Py_INCREF(stream);
|
||||
st->u.private_data = stream;
|
||||
st->vfs = me;
|
||||
if (strchr(io_mode,'r'))
|
||||
st->status = Input_Stream_f;
|
||||
else
|
||||
st->status = Append_Stream_f | Output_Stream_f;
|
||||
Yap_DefaultStreamOps(st);
|
||||
return stream;
|
||||
}
|
||||
|
||||
static bool
|
||||
py_close(int sno) {
|
||||
return true;
|
||||
StreamDesc *s = YAP_GetStreamFromId(sno);
|
||||
PyObject *fclose = PyObject_GetAttrString(s->u.private_data, "close");
|
||||
PyObject *rc = PyObject_CallObject(fclose, NULL);
|
||||
bool v = (rc == Py_True);
|
||||
return v;
|
||||
}
|
||||
|
||||
static int
|
||||
py_put(int sno, int ch) {
|
||||
// PyObject *pyw; // buffer
|
||||
// int pyw_kind;
|
||||
// PyObject *pyw_data;
|
||||
|
||||
char s[2];
|
||||
StreamDesc *st = YAP_GetStreamFromId(sno);
|
||||
// PyUnicode_WRITE(pyw_kind, pyw_data, 0, ch);
|
||||
PyObject *err, *fput = PyObject_GetAttrString(st->u.private_data, "write");
|
||||
s[0] = ch;
|
||||
s[1] = '\0';
|
||||
PyObject_CallFunctionObjArgs(fput, PyBytes_FromString(s), NULL);
|
||||
if ((err = PyErr_Occurred())) {
|
||||
PyErr_SetString(
|
||||
err,
|
||||
"Error in put\n"); // %s:%s:%d!\n", __FILE__, __FUNCTION__, __LINE__);
|
||||
}
|
||||
return ch;
|
||||
}
|
||||
|
||||
static int py_get(int sno) {
|
||||
StreamDesc *s = YAP_GetStreamFromId(sno);
|
||||
PyObject *fget = PyObject_GetAttrString(s->u.private_data, "read");
|
||||
PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL);
|
||||
return PyUnicode_READ_CHAR(pyr, 0);
|
||||
}
|
||||
|
||||
static int py_peek(int sno) {
|
||||
StreamDesc *s = YAP_GetStreamFromId(sno);
|
||||
PyObject *fget = PyObject_GetAttrString(s->u.private_data, "peek");
|
||||
PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL);
|
||||
return PyUnicode_READ_CHAR(pyr, 0);
|
||||
}
|
||||
|
||||
static int64_t py_seek(int sno, int64_t where, int how) {
|
||||
StreamDesc *s = YAP_GetStreamFromId(sno);
|
||||
PyObject *fseek = PyObject_GetAttrString(s->u.private_data, "seek");
|
||||
PyObject *pyr = PyObject_CallFunctionObjArgs(fseek, PyLong_FromLong(where),
|
||||
PyLong_FromLong(how), NULL);
|
||||
return PyLong_AsLong(pyr);
|
||||
}
|
||||
|
||||
static void py_flush(int sno) {
|
||||
StreamDesc *s = YAP_GetStreamFromId(sno);
|
||||
PyObject *flush = PyObject_GetAttrString(s->u.private_data, "flush");
|
||||
PyObject_CallFunction(flush, NULL);
|
||||
}
|
||||
|
||||
#if 0
|
||||
static void python_output(void) {
|
||||
PyObject *stream = string_to_python("sys.stdout", true, NULL);
|
||||
StreamDesc *st = YAP_GetStreamFromId(1);
|
||||
st->u.private_data = stream;
|
||||
st->vfs = &pystream;
|
||||
stream = string_to_python("sys.stderr", true, NULL);
|
||||
st = YAP_GetStreamFromIds(2);
|
||||
st->u.private_data = stream;
|
||||
st->vfs = &pystream;
|
||||
}
|
||||
#endif
|
||||
|
||||
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_READ | VFS_HAS_PREFIX;
|
||||
pystream.prefix = "/python/";
|
||||
pystream.suffix = NULL;
|
||||
pystream.open = py_open;
|
||||
pystream.close = py_close;
|
||||
pystream.get_char = py_get;
|
||||
pystream.peek_char = py_peek;
|
||||
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;
|
||||
|
||||
extern X_API bool python_in_python;
|
||||
@@ -170,7 +46,7 @@ static void add_modules(void) {
|
||||
Py_f2p = PythonLookup("f2p", NULL);
|
||||
if (Py_f2p)
|
||||
Py_INCREF(Py_f2p);
|
||||
init_python_stream();
|
||||
init_python_vfs();
|
||||
}
|
||||
|
||||
static void install_py_constants(void) {
|
||||
|
@@ -31,11 +31,7 @@
|
||||
release_GIL/0,
|
||||
python_threaded/0,
|
||||
prolog_list_to_python_list/3,
|
||||
(:=)/2,
|
||||
(:=)/1,
|
||||
% (<-)/2,
|
||||
% (<-)/1,
|
||||
op(100,fy,$),
|
||||
op(100,fy,$),
|
||||
op(950,fy,:=),
|
||||
op(950,yfx,:=),
|
||||
op(950,fx,<-),
|
||||
@@ -114,41 +110,60 @@ Data types are
|
||||
:- use_module(library(charsio)).
|
||||
:- dynamic python_mref_cache/2, python_obj_cache/2.
|
||||
|
||||
:- multifile user:(:=)/2,
|
||||
user:(:=)/1,
|
||||
user:(<-)/1,
|
||||
user:(<-)/2, user:'()'/1, user:'{}'/1, user:dot_qualified_goal/2, user:import_arg/1.
|
||||
|
||||
|
||||
import( F ) :- catch( python:python_import(F), _, fail ).
|
||||
|
||||
user:dot_qualified_goal(Fs) :- catch( python:python_proc(Fs), _, fail ).
|
||||
|
||||
user:F() :-
|
||||
catch( python:python_proc(F() ), _, fail ).
|
||||
|
||||
|
||||
user(P1,P2) :- !,
|
||||
:= P1,
|
||||
:= P2.
|
||||
|
||||
:= F :- catch( python:python_proc(F), _, fail ).
|
||||
|
||||
:= (P1,P2) :- !,
|
||||
:= P1,
|
||||
:= P2.
|
||||
:= import( F ) :- !, python_import(F).
|
||||
:= F :- python_proc(F).
|
||||
|
||||
V <- F :-
|
||||
user:(:= ) :- catch( python:python_proc(F), _, fail ).
|
||||
|
||||
user:( V := F ) :-
|
||||
python:python_assign(F, V).
|
||||
|
||||
user:(<- F) :-
|
||||
catch( python:python_proc(F), _, fail ).
|
||||
|
||||
user:(V <- F) :-
|
||||
V := F.
|
||||
|
||||
( V := F ) :-
|
||||
python_assign(F, V).
|
||||
|
||||
((<- F)) :-
|
||||
:= F.
|
||||
|
||||
python_import(Module) :-
|
||||
python_import(Module, _).
|
||||
python:python_import(Module) :-
|
||||
python:python_import(Module, _).
|
||||
|
||||
|
||||
python(Exp, Out) :-
|
||||
Out := Exp.
|
||||
|
||||
python_command(Cmd) :-
|
||||
python_run_command(Cmd).
|
||||
|
||||
python:python_run_command(Cmd).
|
||||
|
||||
start_python :-
|
||||
python_import('inspect', _),
|
||||
python:python_import('inspect', _),
|
||||
at_halt(end_python).
|
||||
|
||||
add_cwd_to_python :-
|
||||
unix(getcwd(Dir)),
|
||||
atom_concat(['sys.path.append(\"',Dir,'\")'], Command),
|
||||
python_command(Command),
|
||||
python_command("sys.argv = [\"yap\"]").
|
||||
python:python_command(Command),
|
||||
python:python_command("sys.argv = [\"yap\"]").
|
||||
% done
|
||||
|
||||
:- initialization( load_foreign_files(['YAPPython'], [], init_python_dll), now ).
|
||||
|
@@ -1,7 +1,7 @@
|
||||
%% @file yapi.yap
|
||||
%% @brief support yap shell
|
||||
%%
|
||||
:- start_low_level_trace.
|
||||
%:- start_low_level_trace.
|
||||
:- module(yapi, [
|
||||
python_ouput/0,
|
||||
show_answer/2,
|
||||
@@ -60,7 +60,8 @@ argi(N,I,I1) :-
|
||||
atomic_concat(`A`,I,N),
|
||||
I1 is I+1.
|
||||
|
||||
python_query( Self, String ) :-
|
||||
python_query( Caller, String ) :-
|
||||
Self := Caller.it,
|
||||
atomic_to_term( String, Goal, VarNames ),
|
||||
query_to_answer( Goal, VarNames, Status, Bindings),
|
||||
Self.port := Status,
|
||||
|
@@ -18,11 +18,11 @@ class Engine( YAPEngine ):
|
||||
if self_contained:
|
||||
yap_lib_path = os.path.dirname(__file__)
|
||||
args.setYapShareDir(os.path.join(yap_lib_path, "prolog"))
|
||||
args.setYapLibDir(yap_lib_path)
|
||||
args.setYapPLDIR(yap_lib_path)
|
||||
args.setSavedState(os.path.join(yap_lib_path, "startup.yss"))
|
||||
YAPEngine.__init__(self, args)
|
||||
self.goal(set_prolog_flag('verbose', 'silent'))
|
||||
self.goal(use_module(library('yapi')))
|
||||
self.goal(compile(library('yapi')))
|
||||
self.goal(set_prolog_flag('verbose', 'normal'))
|
||||
|
||||
def run(self, g, m=None):
|
||||
@@ -49,19 +49,22 @@ class Predicate( YAPPredicate ):
|
||||
|
||||
class Goal(object):
|
||||
"""Goal is a predicate instantiated under a specific environment """
|
||||
def __init__(self, g, engine, module="user",program=None, max_answers=None ):
|
||||
self.g = g
|
||||
def __init__(self, engine, g):
|
||||
self.q = engine.query(g)
|
||||
self.e = engine
|
||||
self.port = "call"
|
||||
self.bindings = None
|
||||
|
||||
def __iter__(self):
|
||||
return PrologTableIter( self.e, self.g )
|
||||
return PrologTableIter( self.e, self )
|
||||
|
||||
class PrologTableIter:
|
||||
|
||||
def __init__(self, e, query):
|
||||
def __init__(self, e, g):
|
||||
try:
|
||||
self.e = e
|
||||
self.q = e.query(python_query(self, query))
|
||||
self.g = g
|
||||
self.q = g.q
|
||||
except:
|
||||
print('Error')
|
||||
|
||||
@@ -74,8 +77,8 @@ class PrologTableIter:
|
||||
if not self.q:
|
||||
raise StopIteration()
|
||||
if self.q.next():
|
||||
rc = self.q.bindings
|
||||
if self.q.port == "exit":
|
||||
rc = self.g.bindings
|
||||
if self.g.port == "exit":
|
||||
self.close()
|
||||
return rc
|
||||
else:
|
||||
@@ -98,7 +101,7 @@ global engine, handler
|
||||
|
||||
yap_lib_path = os.path.dirname(__file__)
|
||||
|
||||
use_module = namedtuple('use_module', 'file')
|
||||
compile = namedtuple('compile', 'file')
|
||||
bindvars = namedtuple('bindvars', 'list')
|
||||
library = namedtuple('library', 'list')
|
||||
v = namedtuple( 'v', 'slot')
|
||||
@@ -153,7 +156,7 @@ class YAPShell:
|
||||
|
||||
|
||||
def query_prolog(self, engine, query):
|
||||
import pdb; pdb.set_trace()
|
||||
#import pdb; pdb.set_trace()
|
||||
#
|
||||
# construct a query from a one-line string
|
||||
# q is opaque to Python
|
||||
@@ -174,8 +177,9 @@ class YAPShell:
|
||||
do_ask = True
|
||||
self.e = engine
|
||||
bindings = []
|
||||
g = python_query(self, query)
|
||||
if not self.q:
|
||||
self.it = PrologTableIter( self.e, query )
|
||||
self.it = Goal( engine, g )
|
||||
for bind in self.it:
|
||||
bindings += [bind]
|
||||
if do_ask:
|
||||
|
@@ -37,15 +37,15 @@ from distutils.core import setup
|
||||
|
||||
pjoin = os.path.join
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
packages = []
|
||||
packages = ['yap_kernel','yap_ipython']
|
||||
# pkg_root = pjoin(here, name)
|
||||
|
||||
for d, _, _ in os.walk(pjoin(here, 'yap_kernel')):
|
||||
if os.path.exists(pjoin(d, '__init__.py')):
|
||||
packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
|
||||
for d, _, _ in os.walk(pjoin(here, 'yap_ipython')):
|
||||
if os.path.exists(pjoin(d, '__init__.py')):
|
||||
packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
|
||||
# for d, _, _ in os.walk(pjoin(here, 'yap_kernel')):
|
||||
# if os.path.exists(pjoin(d, '__init__.py')):
|
||||
# packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
|
||||
# for d, _, _ in os.walk(pjoin(here, 'yap_ipython')):
|
||||
# if os.path.exists(pjoin(d, '__init__.py')):
|
||||
# packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
|
||||
|
||||
sys.path.insert(0, here)
|
||||
package_data = {
|
||||
|
@@ -2324,8 +2324,8 @@ class InteractiveShell(SingletonConfigurable):
|
||||
Command to execute (can not end in '&', as background processes are
|
||||
not supported.
|
||||
split : bool, optional
|
||||
If True, split the output into an yap_ipython SList. Otherwise, an
|
||||
yap_ipython LSString is returned. These are objects similar to normal
|
||||
If True, split the output into an IPython SList. Otherwise, an
|
||||
ipython LSString is returned. These are objects similar to normal
|
||||
lists and strings, with a few convenience attributes for easier
|
||||
manipulation of line-based output. You can use '?' on them for
|
||||
details.
|
||||
@@ -2598,7 +2598,7 @@ class InteractiveShell(SingletonConfigurable):
|
||||
with prepended_to_syspath(dname):
|
||||
try:
|
||||
for cell in get_cells():
|
||||
result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
|
||||
result = self.run_cell(cell, silent=False , shell_futures=shell_futures)
|
||||
if raise_exceptions:
|
||||
result.raise_error()
|
||||
elif not result.success:
|
||||
|
@@ -1,3 +1,4 @@
|
||||
|
||||
/**
|
||||
* @file jupyter.yap
|
||||
*
|
||||
@@ -20,30 +21,30 @@
|
||||
%% ).
|
||||
|
||||
|
||||
%:- reexport(library(yapi)).
|
||||
:- reexport(library(yapi)).
|
||||
:- use_module(library(lists)).
|
||||
:- use_module(library(maplist)).
|
||||
:- use_module(library(python)).
|
||||
|
||||
:- python_import(sys).
|
||||
|
||||
jupyter_query(Self, Cell, Line ) :-
|
||||
start_low_level_trace,
|
||||
setup_call_cleanup(
|
||||
enter_cell(Self),
|
||||
jupyter_cell(Self, Cell, Line),
|
||||
exit_cell(Self)
|
||||
).
|
||||
jupyter_query(Caller, Cell, Line ) :-
|
||||
jupyter_cell(Caller, Cell, Line).
|
||||
|
||||
jupyter_cell(_Self, Cell, _) :-
|
||||
jupyter_cell(_Caller, Cell, _) :-
|
||||
jupyter_consult(Cell),
|
||||
fail.
|
||||
jupyter_cell( _Self, _, Line ) :-
|
||||
jupyter_cell( _Caller, _, Line ) :-
|
||||
blank( Line ),
|
||||
!.
|
||||
jupyter_cell( _Self, _, [] ) :- !.
|
||||
jupyter_cell( Self, _, Line ) :-
|
||||
python_query( Self, Line ).
|
||||
jupyter_cell( _Caller, _, [] ) :- !.
|
||||
jupyter_cell( Caller, _, Line ) :-
|
||||
gated_call(
|
||||
enter_cell(call),
|
||||
python_query( Caller, Line ),
|
||||
Port,
|
||||
enter_cell(Port)
|
||||
).
|
||||
|
||||
jupyter_consult(Text) :-
|
||||
blank( Text ),
|
||||
@@ -61,18 +62,31 @@ blankc(' ').
|
||||
blankc('\n').
|
||||
blankc('\t').
|
||||
|
||||
enter_cell(_Self) :-
|
||||
open('/python/input', read, Input, []),
|
||||
open('/python/sys.stdout', append, Output, []),
|
||||
open('/python/sys.stdout', append, Error, []),
|
||||
set_prolog_flag(user_input, Input),
|
||||
set_prolog_flag(user_output, Output),
|
||||
set_prolog_flag(user_error, Error).
|
||||
enter_cell(retry) :-
|
||||
enter_cell(call).
|
||||
enter_cell(call) :-
|
||||
into_cell.
|
||||
enter_cell(fail) :-
|
||||
enter_cell(exit).
|
||||
enter_cell(answer) :-
|
||||
enter_cell(exit).
|
||||
enter_cell(exception(_)) :-
|
||||
enter_cell(exit).
|
||||
enter_cell(external_exception(_)).
|
||||
enter_cell(!).
|
||||
enter_cell(exit) :-
|
||||
nb_setval(jupyter_cell, off),
|
||||
close( user_output).
|
||||
|
||||
exit_cell(_Self) :-
|
||||
close( user_input),
|
||||
close( user_output),
|
||||
close( user_error).
|
||||
|
||||
into_cell :-
|
||||
nb_setval(jupyter_cell, on),
|
||||
open('/python/sys.input', read, _Input, [bom(false)]),
|
||||
open('/python/sys.stdout', append, _Output, []),
|
||||
open('/python/sys.stderr', append, _Error, []),
|
||||
set_prolog_flag(user_input,_Output),
|
||||
set_prolog_flag(user_output,_Output),
|
||||
set_prolog_flag(user_error,_Error).
|
||||
|
||||
|
||||
completions(S, Self) :-
|
||||
@@ -188,14 +202,14 @@ errors( Self, Text ) :-
|
||||
close_events( Self )
|
||||
).
|
||||
|
||||
clauses(Self, Stream) :-
|
||||
clauses(_Self, Stream) :-
|
||||
repeat,
|
||||
read_clause(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
|
||||
% command( Self, Cl ),
|
||||
Cl == end_of_file,
|
||||
!.
|
||||
|
||||
goals(Self, Stream) :-
|
||||
goals(_Self, Stream) :-
|
||||
repeat,
|
||||
read_term(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
|
||||
% command( Self, Cl ),
|
||||
@@ -252,14 +266,14 @@ user:portray_message(_Severity, error(syntax_error(Cause),info(between(_,LN,_),
|
||||
assert( syntax_error(Cause,LN,CharPos,Details) ).
|
||||
user:portray_message(_Severity, error(style_check(_),_) ) :-
|
||||
nb_getval(jupyter_cell, on).
|
||||
|
||||
|
||||
open_events(Self, Text, Stream) :-
|
||||
Self.errors := [],
|
||||
nb_setval( jupyter, on),
|
||||
open_mem_read_stream( Text, Stream ).
|
||||
|
||||
:- initialization( nb_setval( jupyter, off ) ).
|
||||
|
||||
|
||||
close_events( _Self ) :-
|
||||
nb_setval( jupyter, off ),
|
||||
retract( undo(G) ),
|
||||
@@ -271,4 +285,4 @@ close_events( Self ) :-
|
||||
fail.
|
||||
close_events( _ ).
|
||||
|
||||
:- ( start_low_level_trace ).
|
||||
%:- ( start_low_level_trace ).
|
||||
|
@@ -9,20 +9,21 @@ from typing import Iterator, List, Tuple, Iterable, Union
|
||||
from traitlets import Bool, Enum, observe, Int
|
||||
|
||||
try:
|
||||
from yap4py.yapi import Engine
|
||||
from yap4py.yapi import Engine, Goal, EngineArgs, PrologTableIter
|
||||
except:
|
||||
print("Could not load _yap dll.")
|
||||
from yap_ipython.core import interactiveshell
|
||||
from yap_ipython.core.completer import Completer, Completion
|
||||
from yap_ipython.utils.strdispatch import StrDispatch
|
||||
# import yap_ipython.core
|
||||
from traitlets import Instance
|
||||
from yap_ipython.core.inputsplitter import *
|
||||
from yap_ipython.core.inputtransformer import *
|
||||
from yap_ipython.core.interactiveshell import *
|
||||
from pygments import highlight
|
||||
from pygments.lexers.prolog import PrologLexer
|
||||
from pygments.formatters import HtmlFormatter
|
||||
|
||||
from yap_ipython.core import interactiveshell
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
@@ -106,7 +107,6 @@ class YAPInputSplitter(InputSplitter):
|
||||
def validQuery(self, text, line=None):
|
||||
"""Return whether a legal query
|
||||
"""
|
||||
print("valid")
|
||||
if not line:
|
||||
(_,line,_) = self.shell.prolog_cell(text)
|
||||
line = line.strip().rstrip()
|
||||
@@ -114,7 +114,6 @@ class YAPInputSplitter(InputSplitter):
|
||||
return False
|
||||
self.errors = []
|
||||
self.yapeng.mgoal(errors(self, line),"user")
|
||||
print(self.errors)
|
||||
return self.errors != []
|
||||
|
||||
|
||||
@@ -279,7 +278,7 @@ class YAPCompleter(Completer):
|
||||
help="""Activate greedy completion
|
||||
PENDING DEPRECTION. this is now mostly taken care of with Jedi.
|
||||
|
||||
This will enable completion on elements of lists, results of function calls, etc.,
|
||||
This will enable completion on elements of lists, self.results of function calls, etc.,
|
||||
but can be unsafe because the code is actually evaluated on TAB.
|
||||
"""
|
||||
).tag(config=True)
|
||||
@@ -511,8 +510,9 @@ class YAPRun:
|
||||
self.yapeng = Engine()
|
||||
self.yapeng.goal(use_module(library("jupyter")))
|
||||
self.q = None
|
||||
self.run = False
|
||||
self.shell.port = None
|
||||
self.port = "call"
|
||||
self.os = None
|
||||
self.it = None
|
||||
self.shell.yapeng = self.yapeng
|
||||
self._get_exc_info = shell._get_exc_info
|
||||
|
||||
@@ -525,27 +525,37 @@ class YAPRun:
|
||||
self.yapeng.mgoal(errors(self,text),"user")
|
||||
return self.errors
|
||||
|
||||
def jupyter_query(self, s, mx):
|
||||
def jupyter_query(self, s):
|
||||
#
|
||||
# construct a self.query from a one-line string
|
||||
# self.q is opaque to Python
|
||||
iterations = 0
|
||||
bindings = []
|
||||
program,query,_ = self.prolog_cell(s)
|
||||
if query == self.shell.os:
|
||||
q = self.shell.q
|
||||
self.shell.os = None
|
||||
program,query,mx = self.prolog_cell(s)
|
||||
Found = False
|
||||
|
||||
if query != self.os:
|
||||
self.os = None
|
||||
self.iterations = 0
|
||||
pg = jupyter_query( self, program, query)
|
||||
self.it = Goal( self.yapeng, pg)
|
||||
else:
|
||||
q = Goal(jupyter_query(self, query), self.yapeng, module="user",program=program)
|
||||
for q in q:
|
||||
bindings += [q.bindings()]
|
||||
iterations += 1
|
||||
if mx == iterations:
|
||||
break
|
||||
if q:
|
||||
self.shell.os = query
|
||||
self.shell.q = q
|
||||
return bindings
|
||||
mx += self.iterations
|
||||
self.os = s
|
||||
for answ in self.it:
|
||||
found = True
|
||||
self.bindings += [answ]
|
||||
self.iterations += 1
|
||||
if mx == self.iterations:
|
||||
return True, self.bindings
|
||||
port = self.it.port
|
||||
if port == "exit":
|
||||
self.q = None
|
||||
self.os = None
|
||||
return True,self.bindings
|
||||
if port == "fail":
|
||||
self.q = none
|
||||
self.os = None
|
||||
if self.bindings_message:
|
||||
return True,self.bindings
|
||||
|
||||
|
||||
def _yrun_cell(self, raw_cell, store_history=True, silent=False,
|
||||
@@ -563,7 +573,7 @@ class YAPRun:
|
||||
IPython's machinery, this
|
||||
should be set to False.
|
||||
silent : bool
|
||||
If True, avoid side-effects, such as implicit displayhooks and
|
||||
v If True, avoid side-effects, such as implicit displayhooks and
|
||||
and logging. silent=True forces store_history=False.
|
||||
shell_futures : bool
|
||||
If True, the code will share future statements with the interactive
|
||||
@@ -576,7 +586,7 @@ class YAPRun:
|
||||
|
||||
-------
|
||||
|
||||
`result : :class:`ExecutionResult`
|
||||
`self.result : :class:`Executionself.result`
|
||||
"""
|
||||
|
||||
# construct a query from a one-line string
|
||||
@@ -594,22 +604,22 @@ class YAPRun:
|
||||
info = interactiveshell.ExecutionInfo(
|
||||
raw_cell, store_history, silent, shell_futures)
|
||||
|
||||
result = interactiveshell.ExecutionResult(info)
|
||||
self.result = interactiveshell.ExecutionResult(info)
|
||||
|
||||
if (raw_cell == "") or raw_cell.isspace():
|
||||
self.shell.last_execution_succeeded = True
|
||||
return result
|
||||
return self.result
|
||||
|
||||
if silent:
|
||||
store_history = False
|
||||
|
||||
if store_history:
|
||||
result.execution_count = self.shell.execution_count+1
|
||||
self.result .execution_count = self.shell.execution_count+1
|
||||
|
||||
def error_before_exec(value):
|
||||
result.error_before_exec = value
|
||||
self.result .error_before_exec = value
|
||||
self.shell.last_execution_succeeded = False
|
||||
return result
|
||||
return self.result
|
||||
|
||||
self.shell.events.trigger('pre_execute')
|
||||
if not silent:
|
||||
@@ -646,12 +656,10 @@ class YAPRun:
|
||||
except SyntaxError:
|
||||
self.shell.showsyntaxerror( )
|
||||
preprocessing_exc_tuple = sys.exc_info()
|
||||
|
||||
# Store raw and processed history
|
||||
if store_history:
|
||||
self.shell.history_manager.store_inputs(self.shell.execution_count,
|
||||
cell, raw_cell)
|
||||
silent = False
|
||||
if not silent:
|
||||
self.shell.logger.log(cell, raw_cell)
|
||||
# # Display the exception if input processing failed.
|
||||
@@ -681,32 +689,33 @@ class YAPRun:
|
||||
line = txt[1]
|
||||
else:
|
||||
line = ""
|
||||
if len(txt0) == 2:
|
||||
cell = txt0[1]
|
||||
else:
|
||||
cell = ""
|
||||
if linec:
|
||||
self.shell.run_line_magic(magic, line)
|
||||
if len(txt0) == 2:
|
||||
cell = txt0[1]
|
||||
else:
|
||||
cellArea = ""
|
||||
else:
|
||||
self.shell.run_cell_magic(magic, line, cell)
|
||||
return
|
||||
cell = ""
|
||||
# Give the displayhook a reference to our ExecutionResult so it
|
||||
# can fill in the output value.
|
||||
self.shell.displayhook.exec_result = result
|
||||
self.shell.displayhook.exec_result = self.result
|
||||
has_raised = False
|
||||
try:
|
||||
state = None
|
||||
self.shell.bindings = dict = {}
|
||||
state = self.jupyter_query( cell)
|
||||
if cell.strip():
|
||||
state = self.jupyter_query( cell )
|
||||
if state:
|
||||
self.shell.last_execution_succeeded = True
|
||||
result.result = (True, dict)
|
||||
self.result.result = (True, dict)
|
||||
else:
|
||||
self.shell.last_execution_succeeded = True
|
||||
result.result = (True, {})
|
||||
self.result.result = (True, {})
|
||||
except Exception as e:
|
||||
print(e)
|
||||
has_raised = True
|
||||
result.result = False
|
||||
self.result.result = False
|
||||
|
||||
self.shell.last_execution_succeeded = not has_raised
|
||||
|
||||
@@ -724,10 +733,10 @@ class YAPRun:
|
||||
# Each cell is a *single* input, regardless of how many lines it has
|
||||
self.shell.execution_count += 1
|
||||
|
||||
return result
|
||||
return self.result
|
||||
|
||||
def prolog_cell(self,s):
|
||||
""""
|
||||
"""
|
||||
Trasform a text into program+query. A query is the
|
||||
last line if the last line is non-empty and does not terminate
|
||||
on a dot. You can also finish with
|
||||
|
Reference in New Issue
Block a user