jupyter
This commit is contained in:
parent
530246688c
commit
3a36285bb2
@ -233,15 +233,16 @@ static const char * join(const char *s, ...) {
|
||||
CACHE_REGS
|
||||
va_list args;
|
||||
va_start(args , s);
|
||||
int lvl = push_text_stack();
|
||||
char *buf = Malloc(FILENAME_MAX+1);
|
||||
// int lvl = push_text_stack();
|
||||
char *buf = malloc(FILENAME_MAX+1);
|
||||
if (s && s[0])
|
||||
strcpy(buf, s);
|
||||
while (true) {
|
||||
const char *fmt = va_arg(args, char *);
|
||||
if (fmt == NULL) {
|
||||
va_end(args);
|
||||
return pop_output_text_stack(lvl,buf);
|
||||
// return pop_output_text_stack(lvl,buf);
|
||||
return buf;
|
||||
}
|
||||
strcat(buf, fmt);
|
||||
}
|
||||
|
37
CXX/yapq.hh
37
CXX/yapq.hh
@ -38,7 +38,7 @@ class X_API YAPPredicate;
|
||||
class X_API YAPQuery : public YAPPredicate {
|
||||
bool q_open;
|
||||
int q_state;
|
||||
yhandle_t q_handles;
|
||||
yhandle_t q_handles;
|
||||
struct yami *q_p, *q_cp;
|
||||
int q_flags;
|
||||
YAP_dogoalinfo q_h;
|
||||
@ -186,10 +186,9 @@ public:
|
||||
/// @brief Setup all arguments to a new engine
|
||||
struct X_API YAPEngineArgs : YAP_init_args {
|
||||
|
||||
|
||||
public:
|
||||
YAPEngineArgs() {
|
||||
// const std::string *s = new std::string("startup.yss");
|
||||
// const std::string *s = new std::string("startup.yss");
|
||||
Embedded = true;
|
||||
Yap_InitDefaults(this, nullptr, 0, nullptr);
|
||||
#if YAP_PYTHON
|
||||
@ -223,32 +222,21 @@ public:
|
||||
strcpy((char *)LIBDIR, fl);
|
||||
};
|
||||
|
||||
inline const char *getLIBDIR() { return LIBDIR; };
|
||||
|
||||
inline void setSHAREDIR(const char *fl) {
|
||||
SHAREDIR = (const char *)malloc(strlen(fl) + 1);
|
||||
strcpy((char *)SHAREDIR, fl);
|
||||
inline const char *setINPUT_STARTUP(const char *fl) {
|
||||
INPUT_STARTUP = (const char *)malloc(strlen(fl) + 1);
|
||||
strcpy((char *)INPUT_STARTUP, fl);
|
||||
};
|
||||
|
||||
inline const char *getSHAREDIR() { return SHAREDIR; };
|
||||
inline const char *getINPUT_STARTUP() { return INPUT_STARTUP; };
|
||||
|
||||
inline void setOUTPUT_RESTORE(const char *fl) {
|
||||
OUTPUT_STARTUP = (const char *)malloc(strlen(fl) + 1);
|
||||
strcpy((char *)OUTPUT_STARTUP, fl);
|
||||
};
|
||||
|
||||
inline void setINPUT_RESTORE(const char *fl) {
|
||||
STARTUP = (const char *)malloc(strlen(fl) + 1);
|
||||
strcpy((char *)INPUT_STARTUP, fl);
|
||||
};
|
||||
inline const char *getOUTPUT_STARTUP() { return OUTPUT_STARTUP; };
|
||||
|
||||
inline const char *getINPUT_STARTUP() { return INPUT_STARTUP; };
|
||||
|
||||
|
||||
inline void setOUTPUT_RESTORE(const char *fl) {
|
||||
STARTUP = (const char *)malloc(strlen(fl) + 1);
|
||||
strcpy((char *)OUTPUT_STARTUP, fl);
|
||||
};
|
||||
|
||||
inline const char *getINPUT_STARTUP() { return OUTPUT_STARTUP; };
|
||||
|
||||
inline void setBOOTFILE(const char *fl) {
|
||||
inline void setBOOTFILE(const char *fl) {
|
||||
BOOTFILE = (const char *)malloc(strlen(fl) + 1);
|
||||
strcpy((char *)BOOTFILE, fl);
|
||||
};
|
||||
@ -287,7 +275,6 @@ public:
|
||||
inline void setArgv(char **fl) { Argv = fl; };
|
||||
|
||||
inline char **getArgv() { return Argv; };
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
|
@ -2041,9 +2041,9 @@ significant byte first (like Motorola and SPARC, unlike Intel). */
|
||||
#endif
|
||||
|
||||
/* init-time boot */
|
||||
##ifndef YAP_OUTPUT_STARTUP
|
||||
##define YAP_OUTPUT_STARTUP "${CMAKE_BINARY_DIR}/${YAP_STARTUP}"
|
||||
##endif
|
||||
#ifndef YAP_OUTPUT_STARTUP
|
||||
#define YAP_OUTPUT_STARTUP "${CMAKE_BINARY_DIR}/${YAP_STARTUP}"
|
||||
#endif
|
||||
|
||||
/* HP-UX old socket stuff */
|
||||
#ifndef _XOPEN_SOURCE
|
||||
|
@ -2196,7 +2196,7 @@ X_API int PL_initialise(int myargc, char **myargv) {
|
||||
#if BOOT_FROM_SAVED_STATE
|
||||
init_args.STARTUP = "startup.yss";
|
||||
#else
|
||||
init_args.STARTUP = NULL;
|
||||
init_args.INPUT_STARTUP = NULL;
|
||||
#endif
|
||||
init_args.LIBDIR = NULL;
|
||||
init_args.BOOTFILE = NULL;
|
||||
|
@ -31,14 +31,14 @@ 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/");
|
||||
if (strcasestr(name, "/python/") == name)
|
||||
name += strlen("/python/");
|
||||
#else
|
||||
if (strstr(name, "//python/") == name)
|
||||
name += strlen("//python/");
|
||||
if (strstr(name, "/python/") == name)
|
||||
name += strlen("/python/");
|
||||
#endif
|
||||
StreamDesc *st = YAP_RepStreamFromId(sno);
|
||||
fprintf(stderr,"opened %p\n");
|
||||
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)
|
||||
@ -133,8 +133,8 @@ static bool init_python_stream(void) {
|
||||
|
||||
pystream.name = "python stream";
|
||||
pystream.vflags =
|
||||
VFS_CAN_WRITE | VFS_CAN_EXEC | VFS_CAN_SEEK | VFS_HAS_PREFIX;
|
||||
pystream.prefix = "//python/";
|
||||
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;
|
||||
|
@ -1,16 +1,16 @@
|
||||
%% @file yapi.yap
|
||||
%% @brief support yap shell
|
||||
%%
|
||||
|
||||
:- module(yapi, [
|
||||
python_ouput/0,
|
||||
show_answer/2,
|
||||
show_answer/3,
|
||||
yap_query/4,
|
||||
python_query/2,
|
||||
yapi_query/2
|
||||
]).
|
||||
|
||||
:- start_low_level_trace.
|
||||
:- module(yapi, [
|
||||
python_ouput/0,
|
||||
show_answer/2,
|
||||
show_answer/3,
|
||||
yap_query/4,
|
||||
python_query/2,
|
||||
yapi_query/2
|
||||
]).
|
||||
:- stop_low_level_trace.
|
||||
|
||||
:- yap_flag(verbose, verbose).
|
||||
|
||||
|
@ -5,7 +5,7 @@ import keyword
|
||||
# debugging support.
|
||||
# import pdb
|
||||
from collections import namedtuple
|
||||
|
||||
import readline
|
||||
from .yap import *
|
||||
|
||||
|
||||
@ -44,46 +44,48 @@ class EngineArgs( YAPEngineArgs ):
|
||||
class Predicate( YAPPredicate ):
|
||||
""" Interface to Generic Predicate"""
|
||||
|
||||
class Predicate:
|
||||
"""Goal is a predicate instantiated under a specific environment """
|
||||
def __init__( self, name, args, module=None, engine = None):
|
||||
self = namedtuple( name, args )
|
||||
if module:
|
||||
self.p = YAPPredicate( name, len(self), module )
|
||||
else:
|
||||
self.p = YAPPredicate( name, len(self) )
|
||||
self.e = engine
|
||||
def __init__(self, t, module=None):
|
||||
super().__init__(t)
|
||||
|
||||
def goals( self, engine):
|
||||
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
|
||||
self.e = engine
|
||||
|
||||
def __iter__(self):
|
||||
return PrologTableIter(self.e, self.p)
|
||||
|
||||
def holds(self):
|
||||
return self.e.run(self._make_())
|
||||
return PrologTableIter( self.e, self.g )
|
||||
|
||||
class PrologTableIter:
|
||||
|
||||
def __init__(self, e, goal):
|
||||
def __init__(self, e, query):
|
||||
try:
|
||||
self.e = e
|
||||
self.q = e.YAPQuery(goal)
|
||||
self.q = e.query(python_query(self, query))
|
||||
except:
|
||||
print('Error')
|
||||
|
||||
def __iter__(self):
|
||||
# Iterators are iterables too.
|
||||
# Adding this functions to make them so.
|
||||
# - # Adding this functions to make them so.
|
||||
return self
|
||||
|
||||
def next(self):
|
||||
if self.q.next():
|
||||
return goal
|
||||
else:
|
||||
self.q.close()
|
||||
self.q = None
|
||||
def __next__(self):
|
||||
if not self.q:
|
||||
raise StopIteration()
|
||||
if self.q.next():
|
||||
rc = self.q.bindings
|
||||
if self.q.port == "exit":
|
||||
self.close()
|
||||
return rc
|
||||
else:
|
||||
if self.q:
|
||||
self.close()
|
||||
raise StopIteration()
|
||||
|
||||
def close(self):
|
||||
self.q.close()
|
||||
self.q = None
|
||||
|
||||
f2p = {"fails":{}}
|
||||
for i in range(16):
|
||||
@ -148,24 +150,15 @@ def numbervars( q ):
|
||||
class YAPShell:
|
||||
|
||||
|
||||
def answer(self, q):
|
||||
try:
|
||||
self.bindings = {}
|
||||
v = q.next()
|
||||
if v:
|
||||
print( self.bindings )
|
||||
return v
|
||||
except Exception as e:
|
||||
print(e.args[1])
|
||||
return False
|
||||
|
||||
def query_prolog(self, engine, s):
|
||||
# import pdb; pdb.set_trace()
|
||||
|
||||
def query_prolog(self, engine, query):
|
||||
import pdb; pdb.set_trace()
|
||||
#
|
||||
# construct a query from a one-line string
|
||||
# q is opaque to Python
|
||||
#
|
||||
q = engine.query(python_query(self, s))
|
||||
#q = engine.query(python_query(self, s))
|
||||
#
|
||||
# # vs is the list of variables
|
||||
# you can print it out, the left-side is the variable name,
|
||||
@ -179,33 +172,41 @@ class YAPShell:
|
||||
# print( "Error: Variable Name matches a Python Symbol")
|
||||
# return
|
||||
do_ask = True
|
||||
self.port = "call"
|
||||
# launch the query
|
||||
while self.answer(q):
|
||||
if self.port == "exit":
|
||||
# done
|
||||
q.close()
|
||||
return True, True
|
||||
self.e = engine
|
||||
bindings = []
|
||||
if not self.q:
|
||||
self.it = PrologTableIter( self.e, query )
|
||||
for bind in self.it:
|
||||
bindings += [bind]
|
||||
if do_ask:
|
||||
print(bindings)
|
||||
bindings = []
|
||||
s = input("more(;), all(*), no(\\n), python(#) ?").lstrip()
|
||||
if s.startswith(';') or s.startswith('y'):
|
||||
continue
|
||||
elif s.startswith('#'):
|
||||
try:
|
||||
exec(s.lstrip('#'))
|
||||
except:
|
||||
raise
|
||||
elif s.startswith('*') or s.startswith('a'):
|
||||
do_ask = False
|
||||
continue
|
||||
else:
|
||||
break
|
||||
else:
|
||||
s = ";"
|
||||
if s.startswith(';') or s.startswith('y'):
|
||||
continue
|
||||
elif s.startswith('#'):
|
||||
try:
|
||||
exec(s.lstrip('#'))
|
||||
except:
|
||||
raise
|
||||
elif s.startswith('*') or s.startswith('a'):
|
||||
do_ask = False
|
||||
continue
|
||||
else:
|
||||
break
|
||||
if self.q:
|
||||
self.os = query
|
||||
if bindings:
|
||||
return True,bindings
|
||||
print("No (more) answers")
|
||||
q.close()
|
||||
return
|
||||
return False, None
|
||||
|
||||
|
||||
def live(self, engine, **kwargs):
|
||||
loop = True
|
||||
self.q = None
|
||||
while loop:
|
||||
try:
|
||||
s = input("?- ")
|
||||
|
@ -20,7 +20,7 @@
|
||||
%% ).
|
||||
|
||||
|
||||
:- reexport(library(yapi)).
|
||||
%:- reexport(library(yapi)).
|
||||
:- use_module(library(lists)).
|
||||
:- use_module(library(maplist)).
|
||||
:- use_module(library(python)).
|
||||
@ -28,7 +28,8 @@
|
||||
:- python_import(sys).
|
||||
|
||||
jupyter_query(Self, Cell, Line ) :-
|
||||
setup_call_cleanup(
|
||||
start_low_level_trace,
|
||||
setup_call_cleanup(
|
||||
enter_cell(Self),
|
||||
jupyter_cell(Self, Cell, Line),
|
||||
exit_cell(Self)
|
||||
@ -61,15 +62,15 @@ blankc('\n').
|
||||
blankc('\t').
|
||||
|
||||
enter_cell(_Self) :-
|
||||
open('//python/input', read, Input, []),
|
||||
open('//python/sys.stdout', append, Output, []),
|
||||
open('//python/sys.stdout', append, Error, []),
|
||||
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).
|
||||
|
||||
exit_cell(_Self) :-
|
||||
%close( user_input),
|
||||
close( user_input),
|
||||
close( user_output),
|
||||
close( user_error).
|
||||
|
||||
|
@ -106,6 +106,7 @@ 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()
|
||||
@ -524,67 +525,27 @@ class YAPRun:
|
||||
self.yapeng.mgoal(errors(self,text),"user")
|
||||
return self.errors
|
||||
|
||||
def jupyter_query(self, s):
|
||||
def jupyter_query(self, s, mx):
|
||||
#
|
||||
# construct a self.query from a one-line string
|
||||
# self.q is opaque to Python
|
||||
iterations = 0
|
||||
self.shell.bindings = {}
|
||||
if self.q and s != self.os:
|
||||
self.q.close()
|
||||
self.q = None
|
||||
if not self.q:
|
||||
#import pdb; pdb.set_trace()
|
||||
self.shell.port = "call"
|
||||
program,query,_ = self.prolog_cell(s)
|
||||
self.q = self.yapeng.query(jupyter_query(self, program, query))
|
||||
self.shell.Solutions = []
|
||||
if not self.q:
|
||||
return True, []
|
||||
self.os = s
|
||||
# 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, sttrings, In this case
|
||||
# variable names should match strings
|
||||
#for eq in vs:
|
||||
# if not isinstance(eq[0],str):x
|
||||
# print( "Error: Variable Name matches a Python Symbol")
|
||||
# return
|
||||
# ask = True
|
||||
# launch the query
|
||||
# run the new command using the given tracer
|
||||
while True:
|
||||
iterations = iterations - 1
|
||||
rc = YAPRun.answer(self, self.q)
|
||||
if rc:
|
||||
# deterministic = one solution
|
||||
#Dict = {}
|
||||
#engine.goal(show_answer( q.namedVars(), Dict))
|
||||
self.shell.Solutions += [self.shell.bindings]
|
||||
if self.shell.port == "exit":
|
||||
# done
|
||||
self.q.close()
|
||||
self.q = None
|
||||
self.os = ""
|
||||
return True, self.shell.Solutions
|
||||
if iterations == 0:
|
||||
return True, self.shell.Solutions
|
||||
else:
|
||||
print("No (more) answers")
|
||||
self.q.close()
|
||||
self.q = None
|
||||
self.os = ''
|
||||
return True, self.shell.Solutions
|
||||
|
||||
def answer(self, q):
|
||||
try:
|
||||
return q.next()
|
||||
except Exception as e:
|
||||
self.yapeng.goal(exit_cell(self))
|
||||
return False, None
|
||||
bindings = []
|
||||
program,query,_ = self.prolog_cell(s)
|
||||
if query == self.shell.os:
|
||||
q = self.shell.q
|
||||
self.shell.os = None
|
||||
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
|
||||
|
||||
|
||||
def _yrun_cell(self, raw_cell, store_history=True, silent=False,
|
||||
@ -690,9 +651,9 @@ class YAPRun:
|
||||
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.
|
||||
# if preprocessing_exc_tuple is not None:
|
||||
# self.showtraceback(preprocessing_exc_tuple)
|
||||
|
@ -71,10 +71,10 @@ elseif(CMAKE_CROSSCOMPILING)
|
||||
)
|
||||
else ()
|
||||
add_custom_target(STARTUP ALL
|
||||
DEPENDS ${CMAKE_BUILD_DIR}/${YAP_STARTUPFILE}
|
||||
DEPENDS ${CMAKE_TOP_BINARY_DIR}/${YAP_STARTUP}
|
||||
)
|
||||
add_custom_command(OUTPUT ${CMAKE_TOP_BINARY_DIR}/${YAP_STARTUP}
|
||||
COMMAND yap-bin -B${CMAKE_SOURCE_DIR}/pl/boot.yap --output-saved-state=${CMAKE_TOP_BINARY_DIR}/${YAP_STARTUP}
|
||||
COMMAND yap-bin -B
|
||||
VERBATIM
|
||||
DEPENDS ${PL_BOOT_SOURCES} yap-bin
|
||||
)
|
||||
|
@ -365,6 +365,7 @@ system_module(Mod) :-
|
||||
functor(G0, N, K),
|
||||
'$autoloader_find_predicate'(G0,ExportingMod),
|
||||
ExportingMod \= ImportingMod,
|
||||
writeln((ExportingMod,ImportingMod,G0,G0, N ,K)),
|
||||
(recordzifnot('$import','$import'(ExportingMod,ImportingMod,G0,G0, N ,K),_) -> true ; true ).
|
||||
|
||||
|
||||
@ -491,9 +492,11 @@ export_list(Module, List) :-
|
||||
G1=..[N1|Args],
|
||||
( '$check_import'(M0,ContextMod,N1,K) ->
|
||||
( ContextMod == prolog ->
|
||||
recordzifnot('$import','$import'(M0,user,G0,G1,N1,K),_),
|
||||
writeln((M0,ContextMod,G0,G1,N1,K)),
|
||||
recordzifnot('$import','$import'(M0,user,G0,G1,N1,K),_),
|
||||
fail
|
||||
;
|
||||
writeln((M0,ContextMod,G0,G1,N1,K)),
|
||||
recordaifnot('$import','$import'(M0,ContextMod,G0,G1,N1,K),_),
|
||||
fail
|
||||
;
|
||||
|
Reference in New Issue
Block a user