This commit is contained in:
Vitor Santos Costa
2018-06-01 08:37:25 +01:00
parent 7325407d23
commit 725a0a692a
10 changed files with 205 additions and 218 deletions

View File

@@ -13,15 +13,15 @@ static int py_putc(int sno, int ch) {
// PyObject *pyw_data;
StreamDesc *st = YAP_GetStreamFromId(sno);
if (st->user_name == TermOutStream) {
// term_t tg = python_acquire_GIL();
PySys_WriteStdout("%C", ch);
//python_release_GIL(tg);
term_t tg = python_acquire_GIL();
PySys_WriteStdout("%C", ch);
python_release_GIL(tg);
return ch;
}
if (st->user_name == TermErrStream) {
//term_t tg = python_acquire_GIL();
term_t tg = python_acquire_GIL();
PySys_WriteStderr("%C", ch);
//python_release_GIL(tg);
python_release_GIL(tg);
return ch;
}
char s[2];
@@ -62,8 +62,8 @@ static void *py_open(VFS_t *me, const char *name, const char *io_mode,
st->user_name = TermOutStream;
} else if (strcmp(name, "sys.stderr") == 0) {
st->user_name = TermErrStream;
} else if (strcmp(name, "input") == 0) {
pystream = PyObject_Call(pystream, PyTuple_New(0), NULL);
// } else if (strcmp(name, "input") == 0) {
//pystream = PyObject_Call(pystream, PyTuple_New(0), NULL);
} else {
st->user_name = YAP_MkAtomTerm(st->name);
}
@@ -90,16 +90,16 @@ static bool getLine(int inp) {
char *myrl_line = NULL;
StreamDesc *rl_instream = YAP_RepStreamFromId(inp);
term_t ctk = python_acquire_GIL();
fprintf(stderr, "in");
Py_ssize_t size;
PyObject *prompt = PyUnicode_FromString("?- "),
*msg = PyUnicode_FromString(" **input** ");
/* window of vulnerability opened */
myrl_line = PyUnicode_AsUTF8(PyObject_CallFunctionObjArgs(
rl_instream->u.private_data, msg, prompt, NULL));
myrl_line = PyUnicode_AsUTF8AndSize(PyObject_CallFunctionObjArgs(
rl_instream->u.private_data, msg, prompt, NULL), &size);
python_release_GIL(ctk);
rl_instream->u.irl.ptr = rl_instream->u.irl.buf =
(const unsigned char *)myrl_line;
myrl_line = NULL;
(const unsigned char *)malloc(size);
memcpy((void *)rl_instream->u.irl.buf, myrl_line, size);
return true;
}

View File

@@ -73,7 +73,6 @@ python_query( Caller, String ) :-
query_to_answer( Goal, VarNames, Status, Bindings),
atom_to_string( Status, SStatus ),
Caller.port := SStatus,
start_low_level_trace,
write_query_answer( Bindings ),
nl(user_error),
Caller.answer := {},
@@ -88,4 +87,4 @@ in_dict(Dict, nonvar([V0|Vs],G)) :- !,
Dict[V0] := G,
in_dict( Dict, nonvar(Vs, G) ).
in_dict(_Dict, nonvar([],_G)) :- !.
in_dict(_, _).
in_dict(_, _)

View File

@@ -66,17 +66,10 @@ class Query (YAPQuery):
return self
def __next__(self):
if self.port == "exit" or self.port == "fail":
return
else:
if self.next():
return self.port,self.answer
else:
self.close()
def close( self ):
self.engine.reSet()
if self.port == "fail":
raise IndexError()
return self.next()
def name( name, arity):
try:
if arity > 0 and name.isidentifier(): # and not keyword.iskeyword(name):
@@ -141,13 +134,11 @@ class YAPShell:
engine = self.engine
bindings = []
loop = False
if g:
g.release()
g = python_query(self, query)
self.q = Query( engine, g )
for port,bind in self.q:
bindings += [bind]
if port == "exit":
while self.q.next():
bindings += [self.q.answer]
if self.q.port == "exit":
break
if loop:
continue
@@ -189,7 +180,6 @@ class YAPShell:
if not s:
continue
else:
print(s)
self.query_prolog(s)
except SyntaxError as err:
print("Syntax Error error: {0}".format(err))

View File

@@ -34,8 +34,26 @@ jupyter_cell( _Caller, _, Line ) :-
jupyter_cell( _Caller, _, [] ) :- !.
jupyter_cell( Caller, _, Line ) :-
Self := Caller.query,
start_low_level_trace,
python_query( Self, Line ).
gated_call( streams(true),
python_query(Self,Line),
Gate,
restreams(Gate)
).
restreams(redo) :-
streams(true).
restreams(fail) :-
streams(false).
restreams(answer) :-
streams(false).
restreams(exit) :-
streams(false).
restreams(!) :-
streams(false).
restreams(external_exception(_)) :-
streams(false).
restreams(exception) :-
streams(false).
jupyter_consult(Text) :-
blank( Text ),
@@ -58,24 +76,30 @@ blankc('\t').
streams(false) :-
nb_setval(jupyter_cell, false),
fail,
flush_output,
retract(cell_stream(S)),
close(S),
fail.
streams(false).
streams(true) :-
nb_setval(jupyter_cell, true),
fail,
% open('/python/input', read, _Input, [alias(user_input),bom(false)]),
open('/python/sys.stdout', append, Output, [alias(user_output)]),
assert( cell_stream( Output) ),
open('/python/sys.stderr', append, Error, [alias(user_error)]),
nb_setval(jupyter_cell, true),
start_low_level_trace,
\+ current_stream('/python/input',_,_),
open('/python/input', read, Input, [alias(user_input),bom(false),script(false)]),
assert( cell_stream( Input) ),
set_prolog_flag(user_input,Input),
fail.
streams(true) :-
\+ current_stream('/python/sys.stdout',_,_),
open('/python/sys.stdout', append, Output, [alias(user_output)]),
assert( cell_stream( Output) ),
fail.
streams(true) :-
\+ current_stream('/python/sys.stderr',_,_),
open('/python/sys.stderr', append, Error, [alias(user_error)]),
assert( cell_stream( Error) ),
% set_prolog_flag(user_input,_Input),
set_prolog_flag(user_output, Output),
set_prolog_flag(user_error, Error).
set_prolog_flag(user_error, Error),
fail.
streams(true).
ready(_Self, Line ) :-

View File

@@ -41,6 +41,17 @@ streams = namedtuple('streams', ' text' )
global engine
def tracefunc(frame, event, arg, indent=[0]):
if event == "call":
indent[0] += 2
print( "-" * indent[0] + "> call function", frame.f_code.co_name )
elif event == "return":
print( "<" + "-" * indent[0], "exit function", frame.f_code.co_name )
indent[0] -= 2
return tracefunc
import sys
class YAPInputSplitter(InputSplitter):
"""An input splitter that recognizes all of iyap's special syntax."""
@@ -496,10 +507,8 @@ class YAPCompleter(Completer):
self.matches = []
prolog_res = self.shell.yapeng.mgoal(completions(text, self), "user",True)
if self.matches:
print( text, magic_res )
return text, self.matches
magic_res = self.magic_matches(text)
print( text, magic_res )
return text, magic_res
@@ -537,48 +546,43 @@ class YAPRun:
# construct a self.queryuery from a one-line string
# self.query is opaque to Python
try:
print(query,s, file=sys.stderr)
program,query,stop,howmany = self.prolog_cell(s)
program,squery,stop,howmany = self.prolog_cell(s)
found = False
if s != self.os:
self.os = s
# sys.settrace(tracefunc)
if self.query and self.os == squery:
howmany += self.iterations
else:
if self.query:
self.query.close()
self.os = squery
self.iterations = 0
self.bindings = []
pg = jupyter_query( self, program, query)
self.query = self.yapeng.query( pg)
self.query.port = "call"
pg = jupyter_query( self, program, squery)
self.query = self.yapeng.query(pg)
self.query.answer = {}
print("new", file=sys.stderr)
else:
self.query.port = "retry"
self.os = s
howmany += self.iterations
print('old', file=sys.stderr)
while self.query.next():
answer = self.query.answer
found = True
self.bindings += [answer]
self.iterations += 1
if stop and howmany == self.iterations:
return True, self.bindings
if self.query.port == "exit":
self.query.close()
self.query = None
self.os = None
sys.stderr.writeln('Done, with', self.bindings)
return True,self.bindings
if stop or howmany == self.iterations:
return True, self.bindings
if found:
sys.stderr.write('Done, with', self.bindings, '\n')
sys.stderr.writeln('Done, with ', self.bindings)
else:
self.os = None
self.query.close()
self.query = None
self.os = None
sys.stderr.write('Fail\n')
return True,{}
return True,self.bindings
except Exception as e:
sys.stderr.write('Exception after', self.bindings, '\n')
has_raised = True
return False,{}
return False,[]
def _yrun_cell(self, raw_cell, store_history=True, silent=False,
@@ -637,10 +641,10 @@ class YAPRun:
store_history = False
if store_history:
self.result .execution_count = self.shell.execution_count+1
self.result.execution_count = self.shell.execution_count+1
def error_before_exec(value):
self.result .error_before_exec = value
self.result.error_before_exec = value
self.shell.last_execution_succeeded = False
return self.result
@@ -701,7 +705,6 @@ class YAPRun:
if linec:
self.shell.run_line_magic(magic, line)
else:
print("txt0: ",txt0,"\n", file=sys.stderr)
if len(txt0) == 1:
cell = ""
else:
@@ -713,35 +716,29 @@ class YAPRun:
self.shell.displayhook.exec_result = self.result
has_raised = False
try:
state = None
self.bindings = dicts = []
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 )
#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)
#
# run the new command using the given tracer
#
try:
self.yapeng.mgoal(streams(True),"user", True)
#state = tracer.runfunc(f,self,cell)
state = self.jupyter_query( cell )
self.yapeng.mgoal(streams(False),"user", True)
except Exception as e:
has_raised = True
self.yapeng.mgoal(streams(False),"user")
if state:
self.shell.last_execution_succeeded = True
self.result.result = (True, dicts)
else:
self.shell.last_execution_succeeded = True
self.result.result = (True, {})
# def f(self, cell, state):
# state = self.jupyter_query( cell )
# run the new command using the given tracer
#
# self.yapeng.mgoal(streams(True),"user", True)
# tracer.runfunc(f,self,cell,state)
self.jupyter_query( cell )
# state = tracer.runfunc(jupyter_query( self, cell ) )
# self.yapeng.mgoal(streams(False),"user", True)
self.shell.last_execution_succeeded = True
self.result.result = (True, dicts)
except Exception as e:
has_raised = True
self.result.result = False
@@ -772,23 +769,29 @@ class YAPRun:
- whether to stop
- when to stop
"""
i = -1
try:
its = 0
j = 1
while s[i].isdigit():
ch = s[i]
its += j * (ord(ch) - ord('0'))
i-=1
j *= 10;
if s[i] == ';':
if j > 1 or its != 0:
return s[:i], 0 - i, True, its
return s[:i], 0 - i, False, 0
# one solution, stop
return s, 0, True, 1
except:
return s,0, False, 0
l0 = len(s)
i = s.rfind(";")
if i < 0:
its = 1
stop = True
taken = 0
else:
taken = l0-(i-1)
n = s[i+1:].strip()
s = s[:i-1]
if n:
its = 0
j = 0
for ch in n:
if not ch.isdigit():
raise SyntaxError()
its = its*10+ (ord(ch) - ord('0'))
stop = False
else:
stop = False
its = -1
# one solution, stop
return s, taken, stop, its
@@ -809,4 +812,5 @@ class YAPRun:
if query[-1] == '.':
return s,'',False,0
(query, _,loop, sols) = self.clean_end(query)
print(program, query, loop, sols)
return (program, query, loop, sols)