support python interface.

This commit is contained in:
Vitor Santos Costa 2017-02-20 14:38:00 +00:00
parent 5d6ff87d19
commit b17f4967cb
8 changed files with 578 additions and 437 deletions

View File

@ -11,15 +11,18 @@ set (CXX_SOURCES
list(APPEND LIBYAP_SOURCES ${CXX_SOURCES} PARENT_SCOPE) list(APPEND LIBYAP_SOURCES ${CXX_SOURCES} PARENT_SCOPE)
if (ANDROID OR WIN32) if ( WIN32)
add_component (Yap++ ${CXX_SOURCES} ) add_component (YAP++ ${CXX_SOURCES} )
else()
add_external (Yap++ ${CXX_SOURCES} )
MY_target_link_libraries(Yap++ ${CMAKE_DL_LIBS} libYap)
MY_install(TARGETS Yap++ set_property( DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS "_YAP_NOT_INSTALLED_=1;HAVE_CONFIG_H=1;_GNU_SOURCE;YAP_KERNEL=1" )
LIBRARY DESTINATION ${libdir} else()
ARCHIVE DESTINATION ${libdir} add_external (YAP++ ${CXX_SOURCES} )
MY_target_link_libraries(YAP++ ${CMAKE_DL_LIBS} libYap)
MY_install(TARGETS YAP++
LIBRARY DESTINATION ${dlls}
RUNTIME DESTINATION ${dlls}
ARCHIVE DESTINATION ${dlls}
) )
endif() endif()

View File

@ -58,13 +58,13 @@ class YAPAtom {
YAPAtom( Atom at ) { a = at; } YAPAtom( Atom at ) { a = at; }
public: public:
/// construct new YAPAtom from UTF-8 string /// construct new YAPAtom from UTF-8 string
YAPAtom( const char * s) { a = Yap_LookupAtom( s ); } YAPAtom( const char * s) { a = Yap_LookupAtom( s ); }
/// construct new YAPAtom from UTF-8 string /// construct new YAPAtom from UTF-8 string
YAPAtom( const wchar_t * s) { CACHE_REGS a = UTF32ToAtom( s PASS_REGS ); } YAPAtom( const wchar_t * s) { CACHE_REGS a = UTF32ToAtom( s PASS_REGS ); }
/// construct new YAPAtom from wide string /// construct new YAPAtom from wide string
//YAPAtom( const wchar_t * s) { a = Yap_LookupMaybeWideAtom( s ); } //YAPAtom( const wchar_t * s) { a = Yap_LookupMaybeWideAtom( s ); }
/// construct new YAPAtom from max-length string /// construct new YAPAtom from max-length string
YAPAtom( const char * s, size_t len) { a = Yap_LookupAtomWithLength( s, len ); } YAPAtom( const char * s, size_t len) { a = Yap_LookupAtomWithLength( s, len ); }
/// get name of atom /// get name of atom
const char *getName(void); const char *getName(void);
/// get name of (other way) /// get name of (other way)
@ -89,10 +89,11 @@ class YAPProp {
PropTag tag( Prop p ) { return (PropTag)(p->KindOfPE); } PropTag tag( Prop p ) { return (PropTag)(p->KindOfPE); }
public: public:
/// get name of property /// get name of property
virtual YAPAtom name() = 0; // virtual YAPAtom name();
virtual ~YAPProp() {}; virtual ~YAPProp() {};
}; };
#endif /* YAPA_HH */ #endif /* YAPA_HH */

View File

@ -34,14 +34,14 @@ class YAPModule;
*/ */
class YAPModule : protected YAPAtomTerm { class YAPModule : protected YAPAtomTerm {
friend class YAPPredicate; friend class YAPPredicate;
friend class YAPModuleProp;
YAPModule(Term t) : YAPAtomTerm(t){}; YAPModule(Term t) : YAPAtomTerm(t){};
Term t() { return gt(); } Term t() { return gt(); }
Term curModule() { CACHE_REGS return Yap_CurrentModule(); } Term curModule() { CACHE_REGS return Yap_CurrentModule(); }
public: public:
~YAPModule(){}; YAPModule() : YAPAtomTerm(curModule()){};
YAPModule() : YAPAtomTerm(curModule()){}; YAPModule(YAPAtom t) : YAPAtomTerm(t){};
YAPModule(YAPAtom t) : YAPAtomTerm(t){};
}; };
/** /**
@ -54,12 +54,12 @@ class YAPModuleProp : public YAPProp {
ModEntry *m; ModEntry *m;
YAPModuleProp(ModEntry *mod) { m = mod; }; YAPModuleProp(ModEntry *mod) { m = mod; };
YAPModuleProp(Term tmod) { m = Yap_GetModuleEntry(tmod); }; YAPModuleProp(Term tmod) { m = Yap_GetModuleEntry(tmod); };
public: public:
YAPModuleProp() { CACHE_REGS m = Yap_GetModuleEntry(Yap_CurrentModule()); }; YAPModuleProp(YAPModule tmod) { m = Yap_GetModuleEntry(tmod.gt()); };
YAPModuleProp(YAPModule tmod); YAPModuleProp() { CACHE_REGS m = Yap_GetModuleEntry(Yap_CurrentModule()); };
virtual YAPModule module() { return YAPModule(m->AtomOfME); }; virtual YAPModule module() { return YAPModule(m->AtomOfME); };
}; };
/** /**
@ -80,14 +80,14 @@ public:
/// Constructor: receives name as an atom, plus arity /// Constructor: receives name as an atom, plus arity
/// ///
/// This is the default method, and the most popular /// This is the default method, and the most popular
YAPFunctor(YAPAtom at, uintptr_t arity) { f = Yap_MkFunctor(at.a, arity); } YAPFunctor(YAPAtom at, uintptr_t arity) { f = Yap_MkFunctor(at.a, arity); }
/// Constructor: receives name as a string plus arity /// Constructor: receives name as a string plus arity
/// ///
/// Notice that this is designed for ISO-LATIN-1 right now /// Notice that this is designed for ISO-LATIN-1 right now
/// Note: Python confuses the 3 constructors, /// Note: Python confuses the 3 constructors,
/// use YAPFunctorFromString /// use YAPFunctorFromString
inline YAPFunctor(const char *s, uintptr_t arity, bool isutf8 = true) { inline YAPFunctor(const char *s, uintptr_t arity, bool isutf8 = true) {
f = Yap_MkFunctor(Yap_LookupAtom(s), arity); f = Yap_MkFunctor(Yap_LookupAtom(s), arity);
} }
/// Constructor: receives name as a wide string plus arity /// Constructor: receives name as a wide string plus arity
@ -96,19 +96,18 @@ public:
/// ///
/// Note: Python confuses the 3 constructors, /// Note: Python confuses the 3 constructors,
/// use YAPFunctorFromWideString /// use YAPFunctorFromWideString
inline YAPFunctor(const wchar_t *s, uintptr_t arity) { inline YAPFunctor(const wchar_t *s, uintptr_t arity) {
CACHE_REGS f = Yap_MkFunctor(UTF32ToAtom(s PASS_REGS), arity); CACHE_REGS f = Yap_MkFunctor(UTF32ToAtom(s PASS_REGS), arity);
} }
~YAPFunctor(){};
/// Getter: extract name of functor as an atom /// Getter: extract name of functor as an atom
/// ///
/// this is for external usage. /// this is for external usage.
YAPAtom name(void) { return YAPAtom(NameOfFunctor(f)); } YAPAtom name(void) { return YAPAtom(NameOfFunctor(f)); }
/// Getter: extract arity of functor as an unsigned integer /// Getter: extract arity of functor as an unsigned integer
/// ///
/// this is for external usage. /// this is for external usage.
uintptr_t arity(void) { return ArityOfFunctor(f); } uintptr_t arity(void) { return ArityOfFunctor(f); }
}; };
/** /**
@ -133,7 +132,7 @@ protected:
/// It also communicates the array of arguments t[] /// It also communicates the array of arguments t[]
/// and the array of variables /// and the array of variables
/// back to yapquery /// back to yapquery
YAPPredicate(const char *s0, Term &out, Term &names) { YAPPredicate(const char *s0, Term &out, Term &names) {
CACHE_REGS CACHE_REGS
BACKUP_MACHINE_REGS(); BACKUP_MACHINE_REGS();
Term *modp = NULL; Term *modp = NULL;
@ -155,7 +154,7 @@ names = MkVarTerm ();
/// Term constructor for predicates /// Term constructor for predicates
/// ///
/// It is just a call to getPred /// It is just a call to getPred
inline YAPPredicate(Term t) { inline YAPPredicate(Term t) {
CELL *v = NULL; CELL *v = NULL;
ap = getPred(t, v); ap = getPred(t, v);
} }
@ -175,35 +174,34 @@ names = MkVarTerm ();
inline YAPPredicate(PredEntry *pe) { ap = pe; } inline YAPPredicate(PredEntry *pe) { ap = pe; }
public: public:
~YAPPredicate(){};
/// Functor constructor for predicates /// Functor constructor for predicates
/// ///
/// Asssumes that we use the current module. /// Asssumes that we use the current module.
YAPPredicate(YAPFunctor f) { YAPPredicate(YAPFunctor f) {
CACHE_REGS CACHE_REGS
ap = RepPredProp(PredPropByFunc(f.f, Yap_CurrentModule())); ap = RepPredProp(PredPropByFunc(f.f, Yap_CurrentModule()));
} }
/// Functor constructor for predicates, is given a specific module. /// Functor constructor for predicates, is given a specific module.
/// ///
inline YAPPredicate(YAPFunctor f, YAPTerm mod) { inline YAPPredicate(YAPFunctor f, YAPTerm mod) {
ap = RepPredProp(PredPropByFunc(f.f, mod.t)); ap = RepPredProp(PredPropByFunc(f.f, mod.t));
} }
/// Name/arity constructor for predicates. /// Name/arity constructor for predicates.
/// ///
inline YAPPredicate(YAPAtom at, YAPTerm mod) { inline YAPPredicate(YAPAtom at, YAPTerm mod) {
ap = RepPredProp(PredPropByAtom(at.a, mod.t)); ap = RepPredProp(PredPropByAtom(at.a, mod.t));
} }
/// Name/0 constructor for predicates. /// Name/0 constructor for predicates.
/// ///
YAPPredicate(YAPAtom at); YAPPredicate(YAPAtom at);
/// Mod:Name/Arity constructor for predicates. /// Mod:Name/Arity constructor for predicates.
/// ///
inline YAPPredicate(YAPAtom at, uintptr_t arity, YAPModule mod) { inline YAPPredicate(YAPAtom at, uintptr_t arity, YAPModule mod) {
if (arity) { if (arity) {
Functor f = Yap_MkFunctor(at.a, arity); Functor f = Yap_MkFunctor(at.a, arity);
ap = RepPredProp(PredPropByFunc(f, mod.t())); ap = RepPredProp(PredPropByFunc(f, mod.t()));
@ -214,32 +212,32 @@ public:
/// Atom/Arity constructor for predicates. /// Atom/Arity constructor for predicates.
/// ///
YAPPredicate(YAPAtom at, uintptr_t arity); YAPPredicate(YAPAtom at, uintptr_t arity);
/// char */module constructor for predicates. /// char */module constructor for predicates.
/// ///
inline YAPPredicate(const char *at, uintptr_t arity) { inline YAPPredicate(const char *at, uintptr_t arity) {
ap = RepPredProp(PredPropByFunc(Yap_MkFunctor(Yap_LookupAtom(at), arity), ap = RepPredProp(PredPropByFunc(Yap_MkFunctor(Yap_LookupAtom(at), arity),
CurrentModule)); CurrentModule));
}; };
/// char */module constructor for predicates. /// char */module constructor for predicates.
/// ///
inline YAPPredicate(const char *at, uintptr_t arity, YAPTerm mod) { inline YAPPredicate(const char *at, uintptr_t arity, YAPTerm mod) {
ap = RepPredProp( ap = RepPredProp(
PredPropByFunc(Yap_MkFunctor(Yap_LookupAtom(at), arity), mod.t)); PredPropByFunc(Yap_MkFunctor(Yap_LookupAtom(at), arity), mod.t));
}; };
/// char */module constructor for predicates. /// char */module constructor for predicates.
/// ///
inline YAPPredicate(const char *at, YAPTerm mod) { inline YAPPredicate(const char *at, YAPTerm mod) {
ap = RepPredProp(PredPropByAtom(Yap_LookupAtom(at), mod.t)); ap = RepPredProp(PredPropByAtom(Yap_LookupAtom(at), mod.t));
} }
/// module of a predicate /// module of a predicate
/// ///
/// notice that modules are currently treated as atoms, this should change. /// notice that modules are currently treated as atoms, this should change.
YAPModule module() { YAPModule module() {
if (ap->ModuleOfPred == PROLOG_MODULE) if (ap->ModuleOfPred == PROLOG_MODULE)
return YAPModule(AtomProlog); return YAPModule(AtomProlog);
else else
@ -256,6 +254,15 @@ public:
return YAPAtom(NameOfFunctor(ap->FunctorOfPred)); return YAPAtom(NameOfFunctor(ap->FunctorOfPred));
} }
/// functor of predicate
///
/// onlu defined if arity >= 1
YAPFunctor functor() {
if (ap->ArityOfPE)
return YAPFunctor(ap->FunctorOfPred);
return NULL;
}
/// arity of predicate /// arity of predicate
/// ///
/// we return a positive number. /// we return a positive number.
@ -270,15 +277,15 @@ public:
*/ */
class YAPPrologPredicate : public YAPPredicate { class YAPPrologPredicate : public YAPPredicate {
public: public:
YAPPrologPredicate(YAPTerm t) : YAPPredicate(t){}; YAPPrologPredicate(YAPTerm t) : YAPPredicate(t){};
YAPPrologPredicate(const char *s, arity_t arity) : YAPPredicate(s, arity){}; YAPPrologPredicate(const char *s, arity_t arity) : YAPPredicate(s, arity){};
/// add a new clause /// add a new clause
void *assertClause(YAPTerm clause, bool last = true, bool assertClause(YAPTerm clause, bool last = true,
YAPTerm source = YAPTerm()); YAPTerm source = YAPTerm());
/// add a new tuple /// add a new tuple
void *assertFact(YAPTerm *tuple, bool last = true); bool assertFact(YAPTerm *tuple, bool last = true);
/// retract at least the first clause matching the predicate. /// retract at least the first clause matching the predicate.
void *retractClause(YAPTerm skeleton, bool all = false); void *retractClause(YAPTerm skeleton, bool all = false);
/// return the Nth clause (if source is available) /// return the Nth clause (if source is available)
// YAPTerm clause(size_t index, YAPPredicate p) { return YAPTerm(); }; // YAPTerm clause(size_t index, YAPPredicate p) { return YAPTerm(); };
/// return the Nth clause (if source is available) /// return the Nth clause (if source is available)
@ -307,7 +314,7 @@ public:
} }
} }
}; };
YAPFLIP(const char *name, uintptr_t arity, YAPModule module = YAPModule(), YAPFLIP(const char *name, uintptr_t arity, YAPModule module = YAPModule(),
bool backtrackable = false) bool backtrackable = false)
: YAPPredicate(YAPAtom(name), arity, module) { : YAPPredicate(YAPAtom(name), arity, module) {
if (backtrackable) { if (backtrackable) {
@ -316,8 +323,8 @@ public:
YAP_UserCPredicate(name, 0, arity); YAP_UserCPredicate(name, 0, arity);
} }
}; };
bool addCall(CPredicate call) { return Yap_AddCallToFli(ap, call); } bool addCall(CPredicate call) { return Yap_AddCallToFli(ap, call); }
bool addRetry(CPredicate call) { return Yap_AddRetryToFli(ap, call); } bool addRetry(CPredicate call) { return Yap_AddRetryToFli(ap, call); }
bool addCut(CPredicate call) { return Yap_AddCutToFli(ap, call); } bool addCut(CPredicate call) { return Yap_AddCutToFli(ap, call); }
}; };

File diff suppressed because it is too large Load Diff

View File

@ -5,8 +5,10 @@
#include <gmpxx.h> #include <gmpxx.h>
#include <vector> #include <vector>
#include <string>
#include <iostream>
//! @{ //! @{
/** /**
* *
* @defgroup yap-cplus-interface An object oriented interface for YAP. * @defgroup yap-cplus-interface An object oriented interface for YAP.
@ -67,38 +69,6 @@ extern "C" {
// taken from yap_structs.h // taken from yap_structs.h
#include "iopreds.h" #include "iopreds.h"
#ifdef SWIGPYTHON
extern PyObject *yap_to_pythond(YAP_Term t, bool eval);
extern PyObject *term_to_python(yhandle_t t, bool eval);
extern PyObject *deref_term_to_python(yhandle_t t);
X_API bool init_python(void);
extern Term pythonToYAP(PyObject *p);
extern PyObject *py_Main;
extern inline PyObject *AtomToPy(const char *s) {
if (strcmp(s, "true") == 0)
return Py_True;
if (strcmp(s, "false") == 0)
return Py_False;
if (strcmp(s, "none") == 0)
return Py_None;
if (strcmp(s, "[]") == 0)
return PyList_New(0);
else if (strcmp(s, "{}") == 0)
return PyDict_New();
/* return __main__,s */
else if (PyObject_HasAttrString(py_Main, s)) {
return PyObject_GetAttrString(py_Main, s);
}
// no way to translate
return NULL;
}
X_API extern PyObject *yap_to_python(YAP_Term t, bool eval);
#endif
X_API void YAP_UserCPredicate(const char *, YAP_UserCPred, YAP_Arity arity); X_API void YAP_UserCPredicate(const char *, YAP_UserCPred, YAP_Arity arity);
/* void UserCPredicateWithArgs(const char *name, int *fn(), unsigned int arity) /* void UserCPredicateWithArgs(const char *name, int *fn(), unsigned int arity)

View File

@ -7,12 +7,17 @@ class YAPTerm;
/// take information on a Prolog error: /// take information on a Prolog error:
class YAPError { class YAPError {
std::string name, errorClass, info; yap_error_number ID;
std::string goal, info;
int swigcode; int swigcode;
public: public:
/// error handling when receiving the error term YAPError(){
YAPError(){}; //ID = LOCAL_ActiveError->errorNo;
}
/// error handler object with initial data when receiving the error term
YAPError(yap_error_number id, YAPTerm culprit, std::string txt);
/// we just know the error number /// we just know the error number
/// exact error ID /// exact error ID
yap_error_number getID() { return LOCAL_ActiveError->errorNo; }; yap_error_number getID() { return LOCAL_ActiveError->errorNo; };
@ -27,7 +32,7 @@ public:
/// the term that caused the bug /// the term that caused the bug
// YAPTerm getCulprit(LOCAL_ActiveError->errorFile){}; // YAPTerm getCulprit(LOCAL_ActiveError->errorFile){};
/// text describing the Error /// text describing the Error
const char *text(); std::string text();
}; };
#endif #endif

View File

@ -13,12 +13,13 @@ class YAPPredicate;
* interface to a YAP Query; * interface to a YAP Query;
* uses an SWI-like status info internally. * uses an SWI-like status info internally.
*/ */
class YAPQuery : public YAPPredicate { class YAPQuery : public YAPPredicate
{
bool q_open; bool q_open;
int q_state; int q_state;
yhandle_t q_g, q_handles; yhandle_t q_g, q_handles;
struct yami *q_p, *q_cp; struct yami *q_p, *q_cp;
jmp_buf q_env; sigjmp_buf q_env;
int q_flags; int q_flags;
YAP_dogoalinfo q_h; YAP_dogoalinfo q_h;
YAPQuery *oq; YAPQuery *oq;
@ -51,13 +52,14 @@ public:
/// It is given a string, calls the parser and obtains a Prolog term that /// It is given a string, calls the parser and obtains a Prolog term that
/// should be a callable /// should be a callable
/// goal. /// goal.
inline YAPQuery(const char *s) : YAPPredicate(s, goal, names) { inline YAPQuery(const char *s) : YAPPredicate(s, goal, names)
{
BACKUP_H(); BACKUP_H();
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "got game %ld", __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "got game %ld",
LOCAL_CurSlot); LOCAL_CurSlot);
if (!ap) if (!ap)
return; return;
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "%s", vnames.text()); __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "%s", vnames.text());
openQuery(); openQuery();
RECOVER_H(); RECOVER_H();
}; };
@ -65,7 +67,8 @@ public:
/// ///
/// It is given an atom, and a Prolog term that should be a callable /// It is given an atom, and a Prolog term that should be a callable
/// goal, say `main`, `init`, `live`. /// goal, say `main`, `init`, `live`.
inline YAPQuery(YAPAtom g) : YAPPredicate(g) { inline YAPQuery(YAPAtom g) : YAPPredicate(g)
{
goal = YAPAtomTerm(g).gt(); goal = YAPAtomTerm(g).gt();
names = TermNil; names = TermNil;
openQuery(); openQuery();
@ -89,10 +92,10 @@ public:
const char *text(); const char *text();
/// remove alternatives in the current search space, and finish the current /// remove alternatives in the current search space, and finish the current
/// query /// query
void cut();
/// finish the current query: undo all bindings. /// finish the current query: undo all bindings.
void close(); void close();
/// query variables. /// query variables.
void cut();
Term namedVars(); Term namedVars();
/// query variables, but copied out /// query variables, but copied out
Term namedVarsCopy(); Term namedVarsCopy();
@ -101,7 +104,8 @@ public:
/// simple YAP Query; /// simple YAP Query;
/// just calls YAP and reports success or failure, Useful when we just /// just calls YAP and reports success or failure, Useful when we just
/// want things done, eg YAPCommand("load_files(library(lists), )") /// want things done, eg YAPCommand("load_files(library(lists), )")
inline bool command() { inline bool command()
{
bool rc = next(); bool rc = next();
close(); close();
return rc; return rc;
@ -113,7 +117,8 @@ public:
/// This class implements a callback Prolog-side. It will be inherited by the /// This class implements a callback Prolog-side. It will be inherited by the
/// Java or Python /// Java or Python
/// class that actually implements the callback. /// class that actually implements the callback.
class YAPCallback { class YAPCallback
{
public: public:
virtual ~YAPCallback() {} virtual ~YAPCallback() {}
virtual void run() { LOG("callback"); } virtual void run() { LOG("callback"); }
@ -126,7 +131,8 @@ public:
* *
* *
*/ */
class YAPEngine { class YAPEngine
{
private: private:
YAPCallback *_callback; YAPCallback *_callback;
YAP_init_args init_args; YAP_init_args init_args;
@ -153,14 +159,16 @@ public:
/// remove current callback /// remove current callback
void delYAPCallback() { _callback = 0; } void delYAPCallback() { _callback = 0; }
/// set a new callback /// set a new callback
void setYAPCallback(YAPCallback *cb) { void setYAPCallback(YAPCallback *cb)
{
delYAPCallback(); delYAPCallback();
_callback = cb; _callback = cb;
} }
/// execute the callback. /// execute the callback.
////void run() { if (_callback) _callback->run(); } ////void run() { if (_callback) _callback->run(); }
/// execute the callback with a text argument. /// execute the callback with a text argument.
void run(char *s) { void run(char *s)
{
if (_callback) if (_callback)
_callback->run(s); _callback->run(s);
} }
@ -178,22 +186,30 @@ public:
/// current directory for the engine /// current directory for the engine
bool call(YAPPredicate ap, YAPTerm ts[]); bool call(YAPPredicate ap, YAPTerm ts[]);
/// current directory for the engine /// current directory for the engine
bool goalt(YAPTerm t); bool goalt(YAPTerm Yt) { return Yt.term(); };
/// current directory for the engine /// current directory for the engine
bool goal(Term t); bool mgoal(Term t, Term tmod);
/// current directory for the engine
bool goal(Term t)
{
return mgoal(t, CurrentModule);
}
/// reset Prolog state /// reset Prolog state
void reSet(); void reSet();
/// release: assune that there are no stack pointers, just release memory /// release: assune that there are no stack pointers, just release memory
// for last execution // for last execution
void release(); void release();
const char *currentDir() { const char *currentDir()
{
char dir[1024]; char dir[1024];
std::string s = Yap_getcwd(dir, 1024 - 1); std::string s = Yap_getcwd(dir, 1024 - 1);
return s.c_str(); return s.c_str();
}; };
/// report YAP version as a string /// report YAP version as a string
const char *version() { const char *version()
{
std::string s = Yap_version(); std::string s = Yap_version();
return s.c_str(); return s.c_str();
}; };

View File

@ -2,20 +2,9 @@
#ifndef YAPT_HH #ifndef YAPT_HH
#define YAPT_HH 1 #define YAPT_HH 1
#include "config.h"
extern "C" { extern "C" {
Term YAP_ReadBuffer(const char *s, Term *tp); Term YAP_ReadBuffer(const char *s, Term *tp);
#if defined(SWIGPYTHON) && 0 }
#include <Python.h>
extern Term pythonToYAP(PyObject *inp);
#define YAPTerm _YAPTERM
#elifndef HAVE_PYTHON_H
typdef struct { int no_python; } PyObject;
#else
#include <Python.h>
#endif
};
class YAPError; class YAPError;
@ -33,20 +22,13 @@ class YAPTerm {
protected: protected:
yhandle_t t; /// handle to term, equivalent to term_t yhandle_t t; /// handle to term, equivalent to term_t
public:
virtual ~YAPTerm() {
// fprintf(stderr,"-%d,%lx,%p ",t,LOCAL_HandleBase[t] ,HR);
// Yap_DebugPlWriteln(LOCAL_HandleBase[t]); }
// LOCAL_HandleBase[t] = TermFreeTerm;
// while ( LOCAL_HandleBase[LOCAL_CurSlot-1] == TermFreeTerm)
LOCAL_CurSlot--;
};
public:
Term gt() { Term gt() {
CACHE_REGS CACHE_REGS
// fprintf(stderr,"?%d,%lx,%p\n",t,LOCAL_HandleBase[t], HR); // fprintf(stderr,"?%d,%lx,%p\n",t,LOCAL_HandleBase[t], HR);
// Yap_DebugPlWriteln(LOCAL_HandleBase[t]); // Yap_DebugPlWriteln(LOCAL_HandleBase[t]);
return Yap_GetFromSlot(t); return Yap_GetFromSlot(t);
}; };
void mk(Term t0) { void mk(Term t0) {
@ -55,14 +37,12 @@ public:
}; };
YAPTerm(Term tn) { mk(tn); }; YAPTerm(Term tn) { mk(tn); };
YAPTerm(PyObject *inp) {
#ifdef SWIGPYTHON #ifdef SWIGPYTHON
Term tinp = pythonToYAP(inp); // YAPTerm(struct _object *inp) {
t = Yap_InitSlot(tinp); // Term tinp = pythonToYAP(inp);
#else // t = Yap_InitSlot(tinp);
t = 0; //}
#endif #endif
}
/// private method to convert from Term (internal YAP representation) to /// private method to convert from Term (internal YAP representation) to
/// YAPTerm /// YAPTerm
// do nothing constructor // do nothing constructor
@ -75,6 +55,21 @@ public:
Term tp; Term tp;
mk(YAP_ReadBuffer(s, &tp)); mk(YAP_ReadBuffer(s, &tp));
} }
#if 1
/// Term destructor, tries to recover slot
virtual ~YAPTerm() {
// fprintf(stderr,"-%d,%lx,%p ",t,LOCAL_HandleBase[t] ,HR);
if (!t)
return;
Yap_DebugPlWriteln(LOCAL_HandleBase[t]);
LOCAL_HandleBase[t] = TermFreeTerm;
while (LOCAL_HandleBase[LOCAL_CurSlot - 1] == TermFreeTerm) {
LOCAL_CurSlot--;
}
};
#endif
/// construct a term out of an integer (if you know object type use /// construct a term out of an integer (if you know object type use
/// YAPIntegerTerm) /// YAPIntegerTerm)
/// YAPTerm(long int num) { mk(MkIntegerTerm(num)); } /// YAPTerm(long int num) { mk(MkIntegerTerm(num)); }
@ -96,7 +91,7 @@ public:
inline void bind(YAPTerm *b) { LOCAL_HandleBase[t] = b->term(); } inline void bind(YAPTerm *b) { LOCAL_HandleBase[t] = b->term(); }
/// from YAPTerm to Term (internal YAP representation) /// from YAPTerm to Term (internal YAP representation)
/// fetch a sub-term /// fetch a sub-term
Term &operator[](size_t n); Term &operator[](arity_t n);
// const YAPTerm *vars(); // const YAPTerm *vars();
/// this term is == to t1 /// this term is == to t1
virtual bool exactlyEqual(YAPTerm t1) { virtual bool exactlyEqual(YAPTerm t1) {
@ -199,24 +194,24 @@ public:
} }
/// return a string with a textual representation of the term /// return a string with a textual representation of the term
virtual const char *text(){ virtual const char *text() {
CACHE_REGS CACHE_REGS
size_t length = 0; size_t length = 0;
encoding_t enc = LOCAL_encoding; encoding_t enc = LOCAL_encoding;
char *os; char *os;
BACKUP_MACHINE_REGS(); BACKUP_MACHINE_REGS();
if (!(os = Yap_TermToString(Yap_GetFromSlot(t), &length, enc, if (!(os = Yap_TermToString(Yap_GetFromSlot(t), &length, enc,
Handle_vars_f))) { Handle_vars_f))) {
RECOVER_MACHINE_REGS(); RECOVER_MACHINE_REGS();
return 0; return 0;
} }
RECOVER_MACHINE_REGS(); RECOVER_MACHINE_REGS();
length = strlen(os) + 1; length = strlen(os) + 1;
char *sm = (char *)malloc(length + 1); char *sm = (char *)malloc(length + 1);
strcpy(sm, os); strcpy(sm, os);
return sm; return sm;
}; };
/// return a handle to the term /// return a handle to the term
inline yhandle_t handle() { return t; }; inline yhandle_t handle() { return t; };
@ -260,12 +255,17 @@ public:
class YAPApplTerm : public YAPTerm { class YAPApplTerm : public YAPTerm {
friend class YAPTerm; friend class YAPTerm;
YAPApplTerm(Term t0) { mk(t0); } YAPApplTerm(Term t0) { mk(t0); }
public: public:
~YAPApplTerm() {} YAPApplTerm(Functor f, Term ts[]) {
YAPApplTerm(YAPFunctor f, YAPTerm ts[]); BACKUP_MACHINE_REGS();
//YAPApplTerm(const char *s, std::vector<YAPTerm> ts); Term t0 = Yap_MkApplTerm(f, f->ArityOfFE, ts);
//YAPApplTerm(YAPFunctor f); mk(t0);
RECOVER_MACHINE_REGS();
};
YAPApplTerm(YAPFunctor f, YAPTerm ts[]);
YAPApplTerm(const std::string s, std::vector<YAPTerm> ts);
YAPApplTerm(YAPFunctor f);
YAPFunctor getFunctor(); YAPFunctor getFunctor();
Term getArg(arity_t i) { Term getArg(arity_t i) {
BACKUP_MACHINE_REGS(); BACKUP_MACHINE_REGS();
@ -327,8 +327,8 @@ public:
}; };
/** /**
* @brief Floating Point Term * @brief Floating Point Term
*/ */
class YAPFloatTerm : public YAPNumberTerm { class YAPFloatTerm : public YAPNumberTerm {
public: public:
@ -375,8 +375,7 @@ public:
else if (to == TermNil) else if (to == TermNil)
return TermNil; return TermNil;
/* error */ /* error */
Yap_Error(TYPE_ERROR_LIST, t, 0); throw YAPError(TYPE_ERROR_LIST, YAPTerm(to), "");
throw YAPError();
} }
/// copy a list. /// copy a list.
/// ///
@ -418,7 +417,7 @@ class YAPAtomTerm : public YAPTerm {
// Constructor: receives a C-atom; // Constructor: receives a C-atom;
YAPAtomTerm(Atom a) { mk(MkAtomTerm(a)); } YAPAtomTerm(Atom a) { mk(MkAtomTerm(a)); }
YAPAtomTerm(Term t) : YAPTerm(t) { IsAtomTerm(t); } YAPAtomTerm(Term t) : YAPTerm(t) { IsAtomTerm(t); }
public: public:
// Constructor: receives an atom; // Constructor: receives an atom;
YAPAtomTerm(YAPAtom a) : YAPTerm() { mk(MkAtomTerm(a.a)); } YAPAtomTerm(YAPAtom a) : YAPTerm() { mk(MkAtomTerm(a.a)); }
@ -430,15 +429,15 @@ public:
YAPAtomTerm(wchar_t *s); YAPAtomTerm(wchar_t *s);
// Constructor: receives a sequence of n wchar_ts, whatever they may be; // Constructor: receives a sequence of n wchar_ts, whatever they may be;
YAPAtomTerm(wchar_t *s, size_t len); YAPAtomTerm(wchar_t *s, size_t len);
virtual bool isVar() { return false; } /// type check for unbound bool isVar() { return false; } /// type check for unbound
virtual bool isAtom() { return true; } /// type check for atom bool isAtom() { return true; } /// type check for atom
virtual bool isInteger() { return false; } /// type check for integer bool isInteger() { return false; } /// type check for integer
virtual bool isFloat() { return false; } /// type check for floating-point bool isFloat() { return false; } /// type check for floating-point
virtual bool isString() { return false; } /// type check for a string " ... " bool isString() { return false; } /// type check for a string " ... "
virtual bool isCompound() { return false; } /// is a primitive term bool isCompound() { return false; } /// is a primitive term
virtual bool isAppl() { return false; } /// is a structured term bool isAppl() { return false; } /// is a structured term
virtual bool isPair() { return false; } /// is a pair term bool isPair() { return false; } /// is a pair term
virtual bool isGround() { return true; } /// term is ground virtual bool isGround() { return true; } /// term is ground
virtual bool isList() { return gt() == TermNil; } /// [] is a list virtual bool isList() { return gt() == TermNil; } /// [] is a list
// Getter: outputs the atom; // Getter: outputs the atom;
YAPAtom getAtom() { return YAPAtom(AtomOfTerm(gt())); } YAPAtom getAtom() { return YAPAtom(AtomOfTerm(gt())); }