This commit is contained in:
Vitor Santos Costa 2019-04-06 10:07:54 +01:00
parent 186c156a4a
commit 0f1eaa827a
7 changed files with 585 additions and 463 deletions

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,7 @@
optimize_sql/2
]).
:- use_module(lists,[
:- use_module(library(lists),[
append/3,
member/2,
delete/3,

View File

@ -27,15 +27,15 @@
db_my_result_set/1
]).
:- use_module(system,[
:- use_module(library(system),[
system/2
]).
:- use_module(charsio,[
:- use_module(library(charsio),[
read_from_chars/2
]).
:- use_module(terms,[
:- use_module(library(terms),[
term_variables/2
]).

View File

@ -13,6 +13,7 @@ from IPython.core.inputtransformer import *
from IPython.core.interactiveshell import *
from ipython_genutils.py3compat import builtin_mod
import copy
import json
from yap_kernel.displayhook import ZMQShellDisplayHook
@ -535,13 +536,14 @@ class YAPRun(InteractiveShell):
self.engine.mgoal(errors(self,text),"user",True)
return self.errors
def prolog(self, program, squery, howmany, result):
def prolog(self, ccell, result):
#
# construct a self.query from a one-line string
# self.q is opaque to Python
try:
# sys.settrace(tracefunc)
(program, squery, _, howmany) = ccell
if self.q and self.os == (program,squery):
howmany += self.iterations
else:
@ -551,7 +553,6 @@ class YAPRun(InteractiveShell):
self.answers = []
result.result = []
self.os = (program,squery)
self.iterations = 0
pg = jupyter_query(self,program,squery)
self.q = Query(self.engine, pg)
for v in self.q:
@ -614,13 +615,6 @@ class YAPRun(InteractiveShell):
`result : :class:`ExecutionResult`
"""
if store_history:
# Write output to the database. Does nothing unless
# history output logging is enabled.
self.shell.history_manager.store_output(self.shell.execution_count)
# Each cell is a *single* input, regardless of how many lines it has
self.shell.execution_count += 1
# construct a query from a one-line string
# q is opaque to Python
# vs is the list of variables
@ -656,6 +650,8 @@ class YAPRun(InteractiveShell):
# # 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 self.error_before_exec(preprocessing_exc_tuple[2])
# Our own compiler remembers the __future__ environment. If we want to
@ -665,7 +661,7 @@ class YAPRun(InteractiveShell):
self.cell_name = str( self.shell.execution_count)
self.shell.displayhook.exec_result= result
cell = raw_cell.strip()
while cell and cell[0] == '%':
while cell[0] == '%':
if cell[1] == '%':
## cell magic
txt0 = cell[2:].split(maxsplit = 1, sep = '\n')
@ -675,6 +671,7 @@ class YAPRun(InteractiveShell):
except:
magic = cell[2:].strip()
body = ""
linec = False
try:
[magic,line] = magic.split(maxsplit=1)
except:
@ -683,6 +680,7 @@ class YAPRun(InteractiveShell):
result.result = self.shell.run_cell_magic(magic, line, body)
return
else:
linec = True
rcell = cell[1:].strip()
try:
[magic,cell] = rcell.split(maxsplit = 1, sep = '\n')
@ -699,8 +697,9 @@ class YAPRun(InteractiveShell):
# Give the displayhook a reference to our ExecutionResult so it
# can fill in the output value.
self.shell.displayhook.exec_result = result
(program,squery,_ ,howmany) = self.prolog_cell(cell)
if howmany <= 0 and not program:
ccell = self.prolog_cell(cell)
(program,squery,_ ,howmany) = ccell
if howmany == 0 and not program:
return result
if self.syntaxErrors(program+squery+".\n") :
result.result = []
@ -724,7 +723,7 @@ class YAPRun(InteractiveShell):
# run the new command using the given tracer
#
# tracer.runfunc(f,self,cell,state)
answers = self.prolog( program, squery, howmany, result )
answers = self.prolog( ccell, result )
# state = tracer.runfunc(hist
# er_query( self, cell ) )
except Exception as e:
@ -732,7 +731,6 @@ class YAPRun(InteractiveShell):
try:
(etype, value, tb) = e
traceback.print_exception(etype, value, tb)
self.engine.mgoal(streams(False),"user", True)
except:
print(e)
@ -745,26 +743,32 @@ class YAPRun(InteractiveShell):
if not silent:
self.shell.events.trigger('post_run_cell')
if store_history:
# Write output to the database. Does nothing unless
# history output logging is enabled.
self.shell.history_manager.store_output(self.shell.execution_count)
# Each cell is a *single* input, regardless of how many lines it has
self.shell.execution_count += 1
self.engine.mgoal(streams(False),"user", True)
return
def prolog_cell(self, s):
return pcell(s)
return cell_structure(s)
def pcell(s):
def cell_structure(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
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
- `*`: you request all solutions
- ';'[N]: you want an answer; optionally you want N answers
- `*`: you request all solutions
- ';'[N]: you want an answer; optionally you want N answers
If the line terminates on a `*/` or starts on a `%` we assume the line
is a comment.
If the line terminates on a `*/` or starts on a `%` we assume the line
is a comment.
"""
try:
sl = s.splitlines()
@ -780,32 +784,35 @@ def pcell(s):
if line[-1] == '.':
return (s,'','.',0)
query = ''
loop = ''
while i<l:
line = sl[-i-1]
if line.strip() == '':
break
query = line+'\n'+query
query = line+'\n\n'+query
i+=1
reps = 1
reps = 1
if query:
q = query.strip()
c= q.rpartition('?')
if not c[1]:
c= q.rpartition(';')
c= q.rpartition('*')
c2 = c[2].strip()
if c[1] != '*' or (c2!='' and not c2.isdecimal()):
c = q.rpartition('?')
c2 = c[2].strip()
if len(c[1]) == 1 and c[0].strip():
c2 = c[2].strip()
query = c[0]
if c2.isdecimal():
reps = int(c2)
elif c2:
return ('',c[1]+c[2],c[1],-1)
elif c[1] == '?':
reps = 1
if c[1] == '?' and(c2=='' or c2.isdecimal()):
c = q.rpartition(';')
c2 = c[2].strip()
else:
reps = 10000000000
loop = c[1]
c=('','',query)
[q,loop,repeats] = c
if q:
query=q
if repeats.strip().isdecimal():
reps = int(repeats)
sep = sepator
elif loop == '*':
reps = -1
elif loop == '?':
reps = 10
while i<l:
line = sl[-i-1]
if line.strip() != '':
@ -821,10 +828,6 @@ def pcell(s):
try:
(etype, value, tb) = e
traceback.print_exception(etype, value, tb)
return ('','','',-1)
except:
print(e)
return ('','','',-1)

View File

@ -5,12 +5,11 @@
#undef Free
#include <yapi.hh>
#include <vector>
#include <string>
#include <vector>
#include "real.h"
using namespace Rcpp;
class yap4r {
@ -19,29 +18,26 @@ class yap4r {
YAPQuery *q;
std::vector<YAPTerm> args;
bool failed;
public:
SEXP qsexp;
yap4r();
bool query(std::string p_name, GenericVector sexps=R_NilValue, std::string p_module="user");
bool query(std::string p_name, GenericVector sexps = R_NilValue,
std::string p_module = "user");
bool more();
bool done();
SEXP peek(int i);
bool compile(std::string s);
bool library(std::string s);
};
yap4r::yap4r() {
yap4r::yap4r() {
YAPEngineArgs *yargs = new YAPEngineArgs();
yap = new YAPEngine(yargs);
};
bool yap4r::query(std::string p_name, GenericVector sexps, std::string p_module) {
bool yap4r::query(std::string p_name, GenericVector sexps,
std::string p_module) {
if (q) {
q->close();
q = nullptr;
@ -50,21 +46,21 @@ bool yap4r::query(std::string p_name, GenericVector sexps, std::string p_module
arity_t arity;
if (sexps.isNULL()) {
YAPTerm qt = YAPAtomTerm(p_name.c_str());
q = new YAPQuery(qt);
t =qt.handle();
q = new YAPQuery(qt);
t = qt.handle();
} else {
arity = sexps.length();
arity = sexps.length();
std::vector<YAPTerm> args = std::vector<YAPTerm>();
yhandle_t sls = Yap_NewHandles(sexps.length());
for (int i=0; i<sexps.length();i++) {
if (!sexp_to_pl(sls+i, sexps[i]))
return false;
args.push_back( YAPTerm(Yap_GetFromSlot(sls+i)) );
}
YAPFunctor f= YAPFunctor(p_name.c_str(), arity);
YAPAtomTerm mod = YAPAtomTerm(p_module.c_str());
t = YAPApplTerm(p_name.c_str(),args.data()).handle();
q = new YAPQuery(f,mod,args.data());
yhandle_t sls = Yap_NewHandles(sexps.length());
for (int i = 0; i < sexps.length(); i++) {
if (!sexp_to_pl(sls + i, sexps[i]))
return false;
args.push_back(YAPTerm(Yap_GetFromSlot(sls + i)));
}
YAPFunctor f = YAPFunctor(p_name.c_str(), arity);
YAPAtomTerm mod = YAPAtomTerm(p_module.c_str());
t = YAPApplTerm(p_name.c_str(), args.data()).handle();
q = new YAPQuery(f, mod, args.data());
}
if (q == nullptr)
return false;
@ -73,8 +69,8 @@ arity = sexps.length();
failed = true;
q = nullptr;
}
if(rc)
qsexp = term_to_sexp(t, false);
if (rc)
qsexp = term_to_sexp(t, false);
return rc;
}
@ -82,58 +78,53 @@ arity = sexps.length();
bool yap4r::compile(std::string s) {
YAPTerm fs[1];
fs[0] = YAPAtomTerm(s.c_str());
return yap->mgoal(YAPApplTerm("compile",fs).term(), USER_MODULE);
return yap->mgoal(YAPApplTerm("compile", fs).term(), USER_MODULE);
}
bool yap4r::library(std::string s) {
YAPTerm fs[1], l[1];
l[0] = YAPAtomTerm(s.c_str());
fs[0] = YAPApplTerm("library", l);
return yap->mgoal(YAPApplTerm("compile",fs).term(), USER_MODULE);
return yap->mgoal(YAPApplTerm("compile", fs).term(), USER_MODULE);
}
bool yap4r::more() {
bool rc = true;
if (failed)
return false;
if (q)
rc = q->next();
if (!rc) {
failed = true;
}
return rc;
bool yap4r::more() {
bool rc = true;
if (failed)
return false;
if (q)
rc = q->next();
if (!rc) {
failed = true;
}
return rc;
}
bool yap4r::done() {
bool yap4r::done() {
if (failed)
return false;
if (q)
q->cut();
q = NULL;
return true;
}
if (failed)
return false;
if (q)
q->cut();
q = NULL;
return true;
}
SEXP yap4r::peek(int i) {
if (failed || q == nullptr)
return R_MissingArg;
if (i == 0)
return qsexp;
return term_to_sexp(Yap_InitSlot(Yap_XREGS[i]), false);
}
SEXP yap4r::peek(int i) {
if (failed || q==nullptr)
return R_MissingArg;
if (i==0)
return qsexp;
return term_to_sexp(Yap_InitSlot(Yap_XREGS[i]), false);
}
RCPP_MODULE(mod_yap4r) {
class_<yap4r>( "yap4r" )
RCPP_MODULE(mod_yap4r) {
class_<yap4r>("yap4r")
.constructor("create an object encapsulating a Prolog engine")
.method( "query", &yap4r::query, "create an active query within the engine")
.method( "more", &yap4r::more, "ask for an extra solution")
.method( "done", &yap4r::done, "terminate the query")
.method( "compile", &yap4r::compile, "compile the file")
.method( "library", &yap4r::library, "compile the library")
.method( "peek", &yap4r::peek, "load arg[i] into R")
;
.method("query", &yap4r::query,
"create an active query within the engine")
.method("more", &yap4r::more, "ask for an extra solution")
.method("done", &yap4r::done, "terminate the query")
.method("compile", &yap4r::compile, "compile the file")
.method("library", &yap4r::library, "compile the library")
.method("peek", &yap4r::peek, "load arg[i] into R");
}

View File

@ -225,7 +225,35 @@
'$extend_file_search_path'(P).
'$init_path_extensions'.
/**
* @pred top_query(?0 Goal).
*
* run _Goal_ as f it had been called from the Prolog
* top-level.
*/
top_quer(G) :-
'$init_step'(2), % consult
'$init_step'(3), % globals
'$init_step'(4), % check if a saved state,
'$init_step'(5), % queues
'$init_step'(6), % I/O, threads.
'$alarm'(0, 0, _, _),
'$clean_up_dead_clauses',
flush_output,
'$run_toplevel_hooks',
prompt1(' ?- '),
nb_setval('$spy_gn',1),
% stop at spy-points if debugging is on.
nb_setval('$debug_run',off),
nb_setval('$debug_jump',off),
'__NB_setval__'('$trace',off),
nb_setval('$debug_status', state(zip, 0, stop,off)),
set_prolog_flag(break_level, 0).
call(user:G, Error, '$Errors'(Error)).
/**
*
* @}
*/

100
regression/sqlitest.yap Normal file

File diff suppressed because one or more lines are too long