better_jupyter

This commit is contained in:
Vitor Santos Costa 2018-03-19 11:43:14 +00:00
parent 56f47acc49
commit 9194fda6cc
9 changed files with 752 additions and 57 deletions

View File

@ -63,7 +63,7 @@ extern bool init_python_vfs(void);
ATOM_comma, ATOM_builtin, ATOM_V, ATOM_A, ATOM_self, ATOM_nil,
ATOM_brackets, ATOM_curly_brackets;
extern functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1,
extern functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1, FUNCTOR_as2,
FUNCTOR_bin1, FUNCTOR_brackets1, FUNCTOR_comma2, FUNCTOR_dir1,
FUNCTOR_float1, FUNCTOR_int1, FUNCTOR_iter1, FUNCTOR_iter2, FUNCTOR_long1,
FUNCTOR_len1, FUNCTOR_curly1, FUNCTOR_ord1, FUNCTOR_range1, FUNCTOR_range2,

View File

@ -14,13 +14,13 @@ static int py_put(int sno, int ch)
// PyObject *pyw_data;
StreamDesc *st = YAP_GetStreamFromId(sno);
if (st->user_name == TermOutStream) {
PyGILState_STATE tg = python_acquire_GIL();
term_t tg = python_acquire_GIL();
PySys_WriteStdout("%C", ch);
python_release_GIL(tg);
return ch;
}
if (st->user_name == TermErrStream) {
PyGILState_STATE tg = python_acquire_GIL();
term_t tg = python_acquire_GIL();
PySys_WriteStderr("%C", ch);
python_release_GIL(tg);
return ch;
@ -29,7 +29,7 @@ static int py_put(int sno, int ch)
PyObject *err;
s[0] = ch;
s[1] = '\0';
PyGILState_STATE g0 = python_acquire_GIL();
term_t g0 = python_acquire_GIL();
PyObject_CallMethodObjArgs(st->u.private_data, PyUnicode_FromString("write"),
PyUnicode_FromString(s), NULL);
python_release_GIL(g0);
@ -88,10 +88,12 @@ static bool py_close(int sno) {
static bool getLine(int inp) {
char *myrl_line = NULL;
StreamDesc *rl_instream = YAP_RepStreamFromId(inp);
PyObject*prompt = PyUnicode_FromString( "?- "),
term_t ctk = python_acquire_GIL();
PyObject*prompt = PyUnicode_FromString( "?- "),
*msg = PyUnicode_FromString("");
/* window of vulnerability opened */
myrl_line = PyUnicode_AsUTF8(PyObject_CallFunctionObjArgs(rl_instream->u.private_data,msg,prompt,NULL));
python_release_GIL(ctk);
rl_instream->u.irl.ptr = rl_instream->u.irl.buf = (const unsigned char*)myrl_line;
myrl_line = NULL;
return true;

File diff suppressed because one or more lines are too long

View File

@ -9,7 +9,7 @@ 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;
functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1,
functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1, FUNCTOR_as2,
FUNCTOR_bin1, FUNCTOR_brackets1, FUNCTOR_comma2, FUNCTOR_dir1,
FUNCTOR_float1, FUNCTOR_int1, FUNCTOR_iter1, FUNCTOR_iter2, FUNCTOR_long1,
FUNCTOR_len1, FUNCTOR_curly1, FUNCTOR_ord1, FUNCTOR_range1, FUNCTOR_range2,
@ -68,6 +68,7 @@ static void install_py_constants(void) {
FUNCTOR_abs1 = PL_new_functor(PL_new_atom("abs"), 1);
FUNCTOR_all1 = PL_new_functor(PL_new_atom("all"), 1);
FUNCTOR_any1 = PL_new_functor(PL_new_atom("any"), 1);
FUNCTOR_as2 = PL_new_functor(PL_new_atom("as"), 2);
FUNCTOR_bin1 = PL_new_functor(PL_new_atom("bin"), 1);
FUNCTOR_ord1 = PL_new_functor(PL_new_atom("ord"), 1);
FUNCTOR_int1 = PL_new_functor(PL_new_atom("int"), 1);

View File

@ -34,8 +34,8 @@
op(100,fy,$),
op(950,fy,:=),
op(950,yfx,:=),
op(950,fx,<-),
op(950,yfx,<-),
% op(950,fx,<-),
% op(950,yfx,<-),
op(50, yf, []),
op(50, yf, '()'),
op(100, xfy, '.'),
@ -112,8 +112,9 @@ Data types are
:- multifile user:(:=)/2,
user:(:=)/1,
user:(<-)/1,
user:(<-)/2, user:'()'/1, user:'{}'/1, user:dot_qualified_goal/2, user:import_arg/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 ).
@ -139,11 +140,13 @@ user:(:= F) :- 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.
*/
python:python_import(Module) :-
python:python_import(Module, _).

View File

@ -1,3 +1,4 @@
%% @file yapi.yap
%% @brief support yap shell
%%
@ -21,7 +22,9 @@
:- reexport( library(python) ).
:- python_import(yap4py.yapi).
:- python_import(gc).
%:- python_import(gc).
:- meta_predicate( yapi_query(:,+) ).
%:- start_low_level_trace.

View File

@ -2661,7 +2661,6 @@ class InteractiveShell(SingletonConfigurable):
result : :class:`ExecutionResult`
"""
print("go")
result = None
try:
# import trace

View File

@ -62,16 +62,18 @@ blankc('\t').
streams(false) :-
nb_setval(jupyter_cell, false),
flush_output,
forall(
stream_property( S, mode(_) ),
close(S)
).
streams(true) :-
% open('/python/input', read, _Input, [alias(user_input),bom(false)]),
nb_setval(jupyter_cell, true),
open('/python/input', read, _Input, [alias(user_input),bom(false)]),
open('/python/sys.stdout', append, _Output, [alias(user_output)]),
open('/python/sys.stderr', append, _Error, [alias(user_error)]),
% set_prolog_flag(user_input,_Input),
set_prolog_flag(user_input,_Input),
set_prolog_flag(user_output,_Output),
set_prolog_flag(user_error,_Error).

View File

@ -555,9 +555,6 @@ class YAPRun:
self.bindings += [answer]
self.iterations += 1
if stop and howmany == self.iterations:
self.query.close()
self.query = None
self.os = None
return True, self.bindings
if self.query.port == "exit":
self.query.close()
@ -565,13 +562,13 @@ class YAPRun:
self.os = None
sys.stderr.writeln('Done, with', self.bindings)
return True,self.bindings
if self.bindings:
sys.stderr.write('Done, with', self.bindings, '\n')
else:
self.query.close()
self.query = None
self.os = None
if self.bindings:
sys.stderr.write('Done, with', self.bindings, '\n')
else:
sys.stderr.write('Fail\n')
sys.stderr.write('Fail\n')
return True,{}
except Exception as e:
has_raised = True
@ -614,7 +611,7 @@ class YAPRun:
# 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()
#import pdb; pdb.set_trace()
# #pdb.set_trace()
# atom match either symbols, or if no symbol exists, strings, In this case
# variable names should match strings
@ -655,19 +652,6 @@ class YAPRun:
# except SyntaxError:
# preprocessing_exc_tuple = self.shell.syntax_error() # sys.exc_info()
cell = raw_cell # cell has to exist so it can be stored/logged
# else:
# if False and len(cell.splitlines()) == 1:
# # Dynamic transformations - only applied for single line commands
# with self.shell.builtin_trap:
# try:
# # use prefilter_lines to handle trailing newlines
# # restore trailing newline for ast.parse
# cell = self.shell.prefilter_manager.prefilter_lines(cell) + '\n'
# except Exception:
# # don't allow prefilter errors to crash IPython
# preprocessing_exc_tuple = sys.exc_info()
for i in self.syntaxErrors(raw_cell):
try:
(what,lin,_,text) = i
@ -683,18 +667,17 @@ class YAPRun:
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)
# if store_history:
# self.shell.execution_count += 1
# return error_before_exec(preprocessing_exc_tuple[2])
if preprocessing_exc_tuple is not None:
self.showtraceback(preprocessing_exc_tuple)
if store_history:
self.shell.execution_count += 1
return error_before_exec(preprocessing_exc_tuple[2])
# Our own compiler remembers the __future__ environment. If we want to
# run code with a separate __future__ environment, use the default
# compiler
# compiler = self.shell.compile if shell_futures else CachingCompiler()
cell_name = str( self.shell.execution_count)
if cell[0] == '%':
if cell[1] == '%':
linec = False
@ -709,15 +692,15 @@ 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)
else:
print(txt0[1])
self.shell.run_cell_magic(magic, line, txt0[1])
print("txt0: ",txt0,"\n")
if len(txt0) == 1:
cell = ""
else:
body = txt0[1]+'\n'+txt0[2]
self.shell.run_cell_magic(magic, line, body)
cell = ""
# Give the displayhook a reference to our ExecutionResult so it
# can fill in the output value.
@ -729,16 +712,16 @@ class YAPRun:
if cell.strip('\n \t'):
#create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
#ignoredirs=[sys.prefix, sys.exec_prefix],
trace=1,
count=0)
def f(self, cell):
self.jupyter_query( cell )
# tracer = trace.Trace(
# #ignoredirs=[sys.prefix, sys.exec_prefix],
# trace=1,
# count=0)
#
# def f(self, cell):
# self.jupyter_query( cell )
# run the new command using the given tracer
#
#
try:
self.yapeng.mgoal(streams(True),"user")
#state = tracer.runfunc(f,self,cell)
@ -746,7 +729,7 @@ class YAPRun:
self.yapeng.mgoal(streams(False),"user")
except Exception as e:
has_raised = True
self.yapeng.mgoal(streams("off"),"user")
self.yapeng.mgoal(streams("off"),"user")
if state:
self.shell.last_execution_succeeded = True
self.result.result = (True, dicts)