This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.

99 lines
1.8 KiB
C++
Raw Normal View History

2019-03-31 23:23:04 +01:00
#include <Rcpp.h>
#undef Realloc
#undef Malloc
#undef Free
#include <yapi.hh>
#include <vector>
2019-04-02 10:27:37 +01:00
#include <string>
2019-03-31 23:23:04 +01:00
#include "real.h"
using namespace Rcpp;
2019-04-02 10:27:37 +01:00
class yap4r {
2019-03-31 23:23:04 +01:00
YAPEngine *yap;
YAPQuery *q;
std::vector<YAPTerm> args;
bool failed;
public:
2019-04-02 10:27:37 +01:00
yap4r();
bool query(std::string p_name,std::string p_module,Rcpp::GenericVector sexps);
bool more();
bool done();
SEXP peek(int i);
};
2019-03-31 23:23:04 +01:00
2019-04-02 10:27:37 +01:00
yap4r::yap4r() {
2019-03-31 23:23:04 +01:00
YAPEngineArgs *yargs = new YAPEngineArgs();
yap = new YAPEngine(yargs);
};
2019-04-02 10:27:37 +01:00
bool yap4r::query(std::string p_name,std::string p_module,Rcpp::GenericVector sexps) {
2019-03-31 23:23:04 +01:00
if (q) {
q->close();
q = NULL;
}
2019-04-02 10:27:37 +01:00
std::vector<Term> args = std::vector<Term>();
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( Yap_GetFromSlot(sls+i) );
}
2019-03-31 23:23:04 +01:00
YAPTerm qt = YAPApplTerm(p_name,args);
q = new YAPQuery(qt);
return true;
2019-04-02 10:27:37 +01:00
}
2019-03-31 23:23:04 +01:00
2019-04-02 10:27:37 +01:00
bool yap4r::more() {
2019-03-31 23:23:04 +01:00
bool rc = true;
if (failed)
return false;
if (q)
2019-04-02 10:27:37 +01:00
rc = q->next();
2019-03-31 23:23:04 +01:00
if (!rc) {
failed = true;
}
return rc;
}
2019-04-02 10:27:37 +01:00
bool yap4r::done() {
2019-03-31 23:23:04 +01:00
if (failed)
return false;
if (q)
2019-04-02 10:27:37 +01:00
q->cut();
2019-03-31 23:23:04 +01:00
q = NULL;
2019-04-02 10:27:37 +01:00
return true;
}
2019-03-31 23:23:04 +01:00
2019-04-02 10:27:37 +01:00
SEXP yap4r::peek(int i) {
2019-03-31 23:23:04 +01:00
if (failed || q==nullptr)
return R_MissingArg;
2019-04-02 10:27:37 +01:00
return term_to_sexp(Yap_InitSlot(Yap_XREGS[i]), false);
}
2019-03-31 23:23:04 +01:00
RCPP_MODULE(mod_yap4r) {
2019-04-02 10:27:37 +01:00
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( "peek", &yap4r::peek, "load arg[i] into R")
;
2019-03-31 23:23:04 +01:00
}