This commit is contained in:
Vitor Santos Costa
2018-07-09 00:50:00 +01:00
parent db9823d5ef
commit c93944192e
8 changed files with 140 additions and 192 deletions

View File

@@ -46,11 +46,11 @@ foreign_t assign_to_symbol(term_t t, PyObject *e) {
PyObject *dic;
if (!lookupPySymbol(s, NULL, &dic))
dic = py_Main;
Py_INCREF(e);
Py_INCREF(e);
return PyObject_SetAttrString(dic, s, e) == 0;
}
foreign_t python_to_term(PyObject *pVal, term_t t) {
static int python_to_term__(PyObject *pVal, term_t t) {
bool rc = true;
term_t to = PL_new_term_ref();
// fputs(" <<*** ",stderr); PyObject_Print(pVal,stderr,0);
@@ -89,14 +89,17 @@ foreign_t python_to_term(PyObject *pVal, term_t t) {
#else
const char *s = PyUnicode_AsUTF8(pVal);
#endif
// if (PyDict_GetItemString(py_Atoms, s))
// rc = rc && PL_unify_atom_chars(t, s);
// else
rc = rc && PL_unify_atom_chars(t, s);
} else if (PyByteArray_Check(pVal)) {
rc = rc && PL_unify_string_chars(t, PyByteArray_AsString(pVal));
#if PY_MAJOR_VERSION < 3
} else if (PyString_Check(pVal)) {
// if (PyDict_GetItemString(py_Atoms, s))
// rc = rc && PL_unify_atom_chars(t, s);
// else
rc =
rc && (PL_is_string(t) ? PL_unify_string_chars(t, s)
: PL_is_variable(t) ? PL_unify_atom_chars(t, s)
: PL_unify_atom_chars(t, s));
} else if (PyByteArray_Check(pVal)) {
rc = rc && PL_unify_string_chars(t, PyByteArray_AsString(pVal));
#if PY_MAJOR_VERSION < 3
} else if (PyString_Check(pVal)) {
rc = rc && PL_unify_string_chars(t, PyString_AsString(pVal));
#endif
} else if (PyTuple_Check(pVal)) {
@@ -137,7 +140,7 @@ foreign_t python_to_term(PyObject *pVal, term_t t) {
PyErr_Clear();
p = Py_None;
}
rc = rc && python_to_term(p, to);
rc = rc && python_to_term__(p, to);
}
} else {
rc = false;
@@ -154,7 +157,7 @@ foreign_t python_to_term(PyObject *pVal, term_t t) {
if ((obj = PyList_GetItem(pVal, i)) == NULL) {
obj = Py_None;
}
rc = rc && python_to_term(obj, to);
rc = rc && python_to_term__(obj, to);
if (!rc)
return false;
}
@@ -174,10 +177,10 @@ foreign_t python_to_term(PyObject *pVal, term_t t) {
term_t tkey = PL_new_term_ref(), tval = PL_new_term_ref(), tint,
tnew = PL_new_term_ref();
/* do something interesting with the values... */
if (!python_to_term(key, tkey)) {
if (!python_to_term__(key, tkey)) {
continue;
}
if (!python_to_term(value, tval)) {
if (!python_to_term__(value, tval)) {
continue;
}
/* reuse */
@@ -209,18 +212,26 @@ foreign_t python_to_term(PyObject *pVal, term_t t) {
X_API YAP_Term pythonToYAP(PyObject *pVal) {
term_t t = PL_new_term_ref();
if (pVal == NULL || !python_to_term(pVal, t)) {
if (pVal == NULL || !python_to_term__(pVal, t)) {
PL_reset_term_refs(t);
return 0;
}
YAP_Term tt = YAP_GetFromSlot(t);
PL_reset_term_refs(t);
//Py_DECREF(pVal);
// Py_DECREF(pVal);
return tt;
}
PyObject *py_Local, *py_Global;
X_API foreign_t python_to_term(PyObject *pVal, term_t t) {
yap_error_descriptor_t *ctx = malloc(sizeof(yap_error_descriptor_t));
bool newxp = Yap_pushErrorContext(true, ctx);
int rc = python_to_term(pVal, t);
Yap_popErrorContext(newxp, true);
return rc;
}
/**
* assigns the Python RHS to a Prolog term LHS, ie LHS = RHS
*
@@ -317,7 +328,7 @@ bool python_assign(term_t t, PyObject *exp, PyObject *context) {
if (PySequence_Check(o) && PyInt_Check(i)) {
long int j;
j = PyInt_AsLong(i);
return PySequence_SetItem(o, i, exp) == 0;
return PySequence_SetItem(o, i, exp) == 0;
}
#endif
if (PyDict_Check(o)) {

View File

@@ -23,8 +23,12 @@
:- python_import(sys).
jupyter_query(Caller, Cell, Line ) :-
jupyter_cell(Caller, Cell, Line).
jupyter_query(Caller, Prog, Query ) :-
catch(
jupyter_cell(Caller, Prog, Query),
E,
'$Error'(E, top)
).
jupyter_cell(_Caller, Cell, _Line) :-
jupyter_consult(Cell), %stack_dump,
@@ -33,8 +37,8 @@ jupyter_cell( _Caller, _, '' ) :- !.
jupyter_cell( _Caller, _, Line ) :-
blank( Line ),
!.
jupyter_cell( Caller, _, Line ) :-
Self := Caller.query,
jupyter_cell( Self, _, Line ) :-
%Self := Caller.query,
python_query(Self,Line).
restreams(call) :-
@@ -52,143 +56,77 @@ jupyter_consult(Text) :-
blank( Text ),
!.
jupyter_consult(Cell) :-
% Name = 'Inp',
% stream_property(Stream, file_name(Name) ),
% setup_call_cleanup(
open_mem_read_stream( Cell, Stream),
load_files(user:'jupyter cell',[stream(Stream)]).
blank(Text) :-
atom_codes(Text, L),
maplist( code_type(space), L).
blank(Text) :-
atom(Text),
!,
atom_codes(Text, L),
maplist( code_type(space), L).
blank(Text) :-
string(Text),
!,
string_codes(Text, L),
maplist( code_type(space), L).
:- dynamic cell_stream/1.
streams(false) :-
nb_setval(jupyter_cell, false),
retract(cell_stream(S)),
close(S),
fail.
streams(false).
streams(false) :-
nb_setval(jupyter_cell, false),
close(user_input),
close(user_output),
close(user_error).
streams(true) :-
streams( false ),
nb_setval(jupyter_cell, true),
% \+ 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)]),
set_prolog_flag(user_output, 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_error, Error),
fail.
streams(true).
open('/python/input', read, _Input, [alias(user_input),bom(false),script(false)]),
open('/python/sys.stdout', append, _Output, [alias(user_output)]),
open('/python/sys.stderr', append, _Error, [alias(user_error)]).
ready(_Self, Line ) :-
blank( Line ),
!.
ready(Self, Line ) :-
errors( Self, Line ),
\+ syntax_error(_,_).
ready(Self, Cell, P, Q ) :-
catch(
all_clear(Self, Cell, P, Q)
E,
system_error(error,E).
errors( Self, Text ) :-
all_clear( Self, _Cell, P, Q) :-
no_errors( Self, P ),
yap_flag(singleton_variables, Old, false)
no_errors( Self, Q ).
no_errors( _Self, Text ) :-
blank(Text),
no_errors( Self, Text ) :-
setup_call_cleanup(
open_events( Self, Text, Stream),
goals(Self, Stream),
close_events( Self )
open_esh( Self, Text, Stream),
esh(Self, Stream),
close_esh( Self, Stream )
).
clauses(_Self, Stream) :-
esh(Self, Stream) :-
repeat,
read_clause(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
% command( Self, Cl ),
catch(
read_clause(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
Error,
syntax(Self, Error)
),
Cl == end_of_file,
!.
goals(_Self, Stream) :-
repeat,
read_term(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
% command( Self, Cl ),
Cl == end_of_file,
!.
command(_, end_of_file) :- !.
syntax(_Self, E) :- writeln(user_error, E), fail.
syntax(Self, error(syntax_error(Cause),info(between(_,LN,_), _FileName, CharPos, Details))) :-
Self.errors := [t(Cause,LN,CharPos,Details)] + Self.errors,
!.
syntax(_Self, E) :- throw(E).
command( _Self, ( :- op(Prio,Assoc,Name) ) ) :-
addop(Prio,Assoc,Name).
command( _Self, ( :- module(Name, Exports) )) :-
retract( active_module( M0 ) ),
atom_concat( '__m0_', Name, M ),
assert( active_module(M) ),
assert( undo( active_module(M0) ) ),
maplist( addop2(M), Exports).
addop(Prio,Assoc,Name) :-
(
current_op(OPrio, SimilarAssoc, Name),
op(Prio, Assoc, Name),
matched_op(Assoc, SimilarAssoc)
->
assertz( undo(op( OPrio, Assoc, Name ) ) )
;
assertz( undo(op( 0, Assoc, Name ) ) )
).
addop2(M, op(Prio, Assoc, Name)) :-
addop( Prio, Assoc, M:Name ).
matched_op(A, B) :-
optype( A, T),
optype( B, T).
optype(fx,pre).
optype(fy,pre).
optype(xfx,in).
optype(xfy,in).
optype(yfx,in).
optype(yfy,in).
optype(xf,pos).
optype(yf,pos).
:- dynamic user:portray_message/2.
:- multifile user:portray_message/2.
:- dynamic syntax_error/4, undo/1.
user:portray_message(_Severity, error(syntax_error(Cause),info(between(_,LN,_), _FileName, CharPos, Details))) :-
nb_getval(jupyter_cell, on),
assert( syntax_error(Cause,LN,CharPos,Details) ).
user:portray_message(_Severity, error(style_check(_),_) ) :-
nb_getval(jupyter_cell, on).
open_events(Self, Text, Stream) :-
open_esh(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) ),
call(G),
fail.
close_events( Self ) :-
retract( syntax_error( C, L, N, A )),
Self.errors := [t(C,L,N,A)] + Self.errors,
fail.
close_events( _ ).
close_esh( _Self, Stream ) :-
close(Stream).
:- if( current_prolog_flag(apple, true) ).

View File

@@ -23,11 +23,11 @@ library = namedtuple('library', 'list')
v = namedtuple('_', 'slot')
load_files = namedtuple('load_files', 'file ofile args')
python_query = namedtuple('python_query', 'query_mgr string')
jupyter_query = namedtuple('jupyter_query', 'self text query')
jupyter_query = namedtuple('jupyter_query', 'self text p q')
enter_cell = namedtuple('enter_cell', 'self' )
exit_cell = namedtuple('exit_cell', 'self' )
completions = namedtuple('completions', 'txt self' )
errors = namedtuple('errors', 'self text' )
errors = namedtuple('errors', 'self text p q' )
streams = namedtuple('streams', ' text' )
nostreams = namedtuple('nostreams', ' text' )
@@ -114,7 +114,7 @@ class YAPInputSplitter(InputSplitter):
if not line:
line = text.rstrip()
self.errors = []
engine.mgoal(errors(self, line),"user",True)
engine.mgoal(errors(self, text ,text,''),"user",True)
return self.errors != []
@@ -520,7 +520,7 @@ class YAPRun:
self.shell.yapeng = self.yapeng
self._get_exc_info = shell._get_exc_info
def syntaxErrors(self, text):
def syntaxErrors(self, text,program,query):
"""Return whether a legal query
"""
if not text:
@@ -528,8 +528,7 @@ class YAPRun:
if text == self.os:
return self.errors
self.errors=[]
(text,_,_,_) = self.clean_end(text)
self.yapeng.mgoal(errors(self,text),"user",True)
self.yapeng.mgoal(errors(self,text,program,query),"user",True)
return self.errors
def jupyter_query(self, s):
@@ -655,7 +654,8 @@ 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
for i in self.syntaxErrors(raw_cell):
(text,program,query,_) = self.clean_end(raw_cell)
for i in self.syntaxErrors(raw_cell,raw_cell,''):
try:
(what,lin,_,text) = i
e = SyntaxError(what, ("<string>", lin, 1, text))