python support

This commit is contained in:
Vitor Santos Costa 2017-05-27 22:54:00 +01:00
parent 25a2b68b15
commit 0c46c894d3
46 changed files with 273711 additions and 118760 deletions

View File

@ -642,7 +642,7 @@ Prop Yap_NewPredPropByFunctor(FunctorEntry *fe, Term cur_mod) {
p->ArityOfPE = fe->ArityOfFE;
p->cs.p_code.FirstClause = p->cs.p_code.LastClause = NULL;
p->cs.p_code.NOfClauses = 0;
p->PredFlags = 0L;
p->PredFlags = UndefPredFlag;
p->src.OwnerFile = Yap_source_file_name();
p->OpcodeOfPred = UNDEF_OPCODE;
p->CodeOfPred = p->cs.p_code.TrueCodeOfPred = (yamop *)(&(p->OpcodeOfPred));
@ -782,7 +782,7 @@ Prop Yap_NewPredPropByAtom(AtomEntry *ae, Term cur_mod) {
p->StatisticsForPred = NULL;
p->cs.p_code.FirstClause = p->cs.p_code.LastClause = NULL;
p->cs.p_code.NOfClauses = 0;
p->PredFlags = 0L;
p->PredFlags = UndefPredFlag;
p->src.OwnerFile = Yap_source_file_name();
p->OpcodeOfPred = UNDEF_OPCODE;
p->cs.p_code.ExpandCode = EXPAND_OP_CODE;

View File

@ -2401,7 +2401,7 @@ YAP_file_type_t YAP_Init(YAP_init_args *yap_init) {
}
#endif
Yap_InitWorkspace(Heap, Stack, Trail, Atts, yap_init->MaxTableSpaceSize,
Yap_InitWorkspace(yap_init, Heap, Stack, Trail, Atts, yap_init->MaxTableSpaceSize,
yap_init->NumberWorkers, yap_init->SchedulerLoop,
yap_init->DelayedReleaseLoad);
//
@ -3266,13 +3266,15 @@ size_t YAP_UTF8_TextLength(Term t) {
} else {
c = '\0';
}
sz += utf8proc_encode_char(c, dst);
t = TailOfTerm(t);
}
} else if (IsAtomTerm(t)) {
Atom at = AtomOfTerm(t);
sz = strlen(RepAtom(at)->StrOfAE);
} else if (IsStringTerm(t)) {
Atom at = AtomOfTerm(t);
char *s = RepAtom(at)->StrOfAE;
sz = strlen(s);
} else if (IsStringTerm(t)) {
sz = strlen(StringOfTerm(t));
}
return sz;
@ -3392,6 +3394,8 @@ X_API Int YAP_FunctorToInt(Functor f) {
return FunctorTranslations - 1;
}
X_API void * YAP_foreign_stream(int sno){ return GLOBAL_Stream[sno].u.private_data; }
X_API Functor YAP_IntToFunctor(Int i) { return TR_Functors[i]; }
X_API void *YAP_shared(void) { return LOCAL_shared; }

View File

@ -1020,6 +1020,7 @@ static void retract_all(PredEntry *p, int in_use) {
p->OpcodeOfPred = FAIL_OPCODE;
} else {
p->OpcodeOfPred = UNDEF_OPCODE;
p->PredFlags |= UndefPredFlag;
}
p->cs.p_code.TrueCodeOfPred = p->CodeOfPred = (yamop *)(&(p->OpcodeOfPred));
if (trueGlobalPrologFlag(PROFILING_FLAG)) {
@ -1664,7 +1665,7 @@ bool Yap_constPred(PredEntry *p) {
return false;
}
}
return false;
}
@ -1809,6 +1810,7 @@ bool Yap_addclause(Term t, yamop *cp, Term tmode, Term mod, Term *t4ref)
p->PredFlags = p->PredFlags | CompiledPredFlag;
}
if (p->cs.p_code.FirstClause == NULL) {
p->PredFlags &= ~UndefPredFlag;
if (!(pflags & DynamicPredFlag)) {
add_first_static(p, cp, spy_flag);
/* make sure we have a place to jump to */
@ -1910,6 +1912,7 @@ void Yap_EraseStaticClause(StaticClause *cl, PredEntry *ap, Term mod) {
/* got rid of all clauses */
ap->cs.p_code.LastClause = ap->cs.p_code.FirstClause = NULL;
ap->OpcodeOfPred = UNDEF_OPCODE;
ap->PredFlags |= UndefPredFlag;
ap->cs.p_code.TrueCodeOfPred = (yamop *)(&(ap->OpcodeOfPred));
} else {
yamop *ncl = cl->ClNext->ClCode;
@ -1978,6 +1981,7 @@ void Yap_add_logupd_clause(PredEntry *pe, LogUpdClause *cl, int mode) {
Yap_AddClauseToIndex(pe, cp, mode == asserta);
}
if (pe->cs.p_code.FirstClause == NULL) {
pe->PredFlags &= ~UndefPredFlag;
add_first_static(pe, cp, FALSE);
/* make sure we have a place to jump to */
if (pe->OpcodeOfPred == UNDEF_OPCODE ||
@ -2663,6 +2667,7 @@ static Int p_mk_d(USES_REGS1) { /* '$make_dynamic'(+P) */
}
if (pe->OpcodeOfPred == UNDEF_OPCODE) {
pe->OpcodeOfPred = FAIL_OPCODE;
pe->PredFlags &= ~UndefPredFlag;
}
pe->src.OwnerFile = Yap_ConsultingFile(PASS_REGS1);
pe->PredFlags |= LogUpdatePredFlag;
@ -2820,7 +2825,7 @@ static Int p_kill_dynamic(USES_REGS1) { /* '$kill_dynamic'(P,M) */
pe->OpcodeOfPred = UNDEF_OPCODE;
pe->cs.p_code.TrueCodeOfPred = pe->CodeOfPred =
(yamop *)(&(pe->OpcodeOfPred));
pe->PredFlags = 0;
pe->PredFlags = UndefPredFlag;
UNLOCKPE(62, pe);
return (TRUE);
}

View File

@ -75,8 +75,8 @@ static void SetOp(int, int, char *, Term);
static void InitOps(void);
static void InitDebug(void);
static void CleanBack(PredEntry *, CPredicate, CPredicate, CPredicate);
static void InitStdPreds(void);
static void InitCodes(void);
static void InitStdPreds(struct yap_boot_params *yapi);
static void InitCodes(struct yap_boot_params *yapi);
static void InitVersion(void);
void exit(int);
static void InitWorker(int wid);
@ -980,12 +980,13 @@ void Yap_InitCPredBack_(const char *Name, arity_t Arity, arity_t Extra,
}
}
static void InitStdPreds(void) {
static void InitStdPreds(struct yap_boot_params *yapi)
{
Yap_InitCPreds();
Yap_InitBackCPreds();
BACKUP_MACHINE_REGS();
Yap_InitFlags(false);
Yap_InitPlIO();
Yap_InitPlIO(yapi);
#if HAVE_MPE
Yap_InitMPE();
#endif
@ -1268,7 +1269,8 @@ struct worker_local *Yap_local;
struct worker_local Yap_local;
#endif
static void InitCodes(void) {
static void InitCodes(struct yap_boot_params *yapi)
{
CACHE_REGS
#if THREADS
int wid;
@ -1315,9 +1317,11 @@ const char *Yap_version(void) {
return RepAtom(AtomOfTerm(t))->StrOfAE;
}
void Yap_InitWorkspace(UInt Heap, UInt Stack, UInt Trail, UInt Atts,
void Yap_InitWorkspace(struct yap_boot_params *yapi,
UInt Heap, UInt Stack, UInt Trail, UInt Atts,
UInt max_table_size, int n_workers, int sch_loop,
int delay_load) {
int delay_load)
{
CACHE_REGS
/* initialize system stuff */
@ -1399,7 +1403,7 @@ void Yap_InitWorkspace(UInt Heap, UInt Stack, UInt Trail, UInt Atts,
#else
Yap_InitAbsmi();
#endif
InitCodes();
InitCodes(yapi);
InitOps();
InitDebug();
InitVersion();
@ -1429,7 +1433,7 @@ void Yap_InitWorkspace(UInt Heap, UInt Stack, UInt Trail, UInt Atts,
GLOBAL_AllowTrailExpansion = true;
Yap_InitExStacks(0, Trail, Stack);
Yap_InitYaamRegs(0);
InitStdPreds();
InitStdPreds(yapi);
/* make sure tmp area is available */
{ Yap_ReleasePreAllocCodeSpace(Yap_PreAllocCodeSpace()); }
}

View File

@ -116,7 +116,7 @@
}
pen = RepPredProp(PredPropByFunc(f, mod));
execute_pred_f:
if (pen->PredFlags & MetaPredFlag) {
if (pen->PredFlags & (MetaPredFlag|UndefPredFlag)) {
/* just strip all of M:G */
if (f == FunctorModule) {
Term tmod = ArgOfTerm(1,d0);
@ -242,7 +242,7 @@
if (DEPTH <= MkIntTerm(1)) {/* I assume Module==0 is primitives */
if (pen->ModuleOfPred) {
if (DEPTH == MkIntTerm(0)) {
FAIL();
FAIL();
} else {
DEPTH = RESET_DEPTH();
}

View File

@ -1,4 +1,5 @@
#define YAP_CPP_INTERFACE 1
#include "yapi.hh"
@ -162,28 +163,28 @@ YAPStringTerm::YAPStringTerm(wchar_t *s, size_t len)
RECOVER_H();
}
YAPApplTerm::YAPApplTerm(YAPFunctor f, YAPTerm ts[]) : YAPTerm()
YAPApplTerm::YAPApplTerm(YAPFunctor f, YAPTerm ts[])
{
BACKUP_H();
arity_t arity = ArityOfFunctor(f.f);
Term *tt = new Term[arity];
Term o = Yap_MkNewApplTerm(f.f, arity);
Term *tt = RepAppl(o)+1;
for (arity_t i = 0; i < arity; i++)
tt[i] = ts[i].term();
mk(Yap_MkApplTerm(f.f, arity, tt));
delete[] tt;
mk(o);
RECOVER_H();
}
YAPApplTerm::YAPApplTerm(std::string f, std::vector<YAPTerm> ts) : YAPTerm()
YAPApplTerm::YAPApplTerm(std::string f, std::vector<YAPTerm> ts)
{
BACKUP_H();
arity_t arity = ts.size();
std::vector<Term> tt(arity);
Functor ff = Yap_MkFunctor(Yap_LookupAtom(f.c_str()),arity);
Term o = Yap_MkNewApplTerm(ff, arity);
Term *tt = RepAppl(o)+1;
for (arity_t i = 0; i < arity; i++)
tt[i] = ts[i].term();
Functor ff = Yap_MkFunctor(Yap_LookupAtom(f.c_str()), arity);
t = Yap_MkApplTerm(ff, arity, &tt[0]);
RECOVER_H();
mk(o);
}
YAPApplTerm::YAPApplTerm(YAPFunctor f) : YAPTerm()
@ -415,21 +416,11 @@ YAPVarTerm::YAPVarTerm()
const char *YAPAtom::getName(void) { return Yap_AtomToUTF8Text(a, nullptr); }
void YAPQuery::openQuery(Term t)
void YAPQuery::openQuery(Term t, Term *ts)
{
CACHE_REGS
arity_t arity = ap->ArityOfPE;
if (arity)
{
Term *ts;
if (IsPairTerm(t))
{
ts = RepPair(t);
}
else
{
ts = RepAppl(t) + 1;
}
if (ts) {
arity_t arity = ap->ArityOfPE;
for (arity_t i = 0; i < arity; i++)
{
XREGS[i + 1] = ts[i];
@ -592,7 +583,7 @@ Term YAPEngine::fun(Term t)
q.cp = CP;
// make sure this is safe
yhandle_t o = Yap_InitHandle(XREGS[arity]);
// allow Prolog style exceotion handling
// allow Prolog style exception handling
LOCAL_RestartEnv = &q_env;
if (sigsetjmp(q_env, false))
{
@ -624,9 +615,20 @@ YAPQuery::YAPQuery(YAPFunctor f, YAPTerm mod, YAPTerm ts[])
{
/* ignore flags for now */
BACKUP_MACHINE_REGS();
goal = YAPApplTerm(f, ts);
CELL *nts;
Term goal;
if (ts) {
goal = Yap_MkApplTerm(f.f, f.arity(), nts);
nts = RepAppl(goal)+1;
} else {
goal = MkVarTerm();
nts = nullptr;
}
openQuery(goal, nts);
names = YAPPairTerm( TermNil );
openQuery(goal.term());
RECOVER_MACHINE_REGS();
}
@ -634,19 +636,54 @@ YAPQuery::YAPQuery(YAPFunctor f, YAPTerm mod, YAPTerm ts[])
YAPQuery::YAPQuery(YAPFunctor f, YAPTerm ts[]) : YAPPredicate(f) {
/* ignore flags for now */
BACKUP_MACHINE_REGS();
goal = YAPTerm( YAPApplTerm(f, ts).gt() );
names.= YAPPairTerm( TermNil );
openQuery(goal.term());
CELL *nts;
if (ts) {
goal = YAPApplTerm(f, nts);
} else {
goal = YAPVarTerm();
nts = nullptr;
}
names = YAPPairTerm( TermNil );
openQuery(goal.term(), nts);
RECOVER_MACHINE_REGS();
}
#endif
YAPQuery::YAPQuery(YAPPredicate p, YAPTerm ts[]) : YAPPredicate(p.ap)
YAPQuery::YAPQuery(YAPTerm t) : YAPPredicate(t)
{
BACKUP_MACHINE_REGS();
goal = YAPApplTerm(YAPFunctor(p.ap->FunctorOfPred), ts);
CELL *nts;
Term tt = t.term();
goal = t;
if (IsApplTerm(tt)) {
Functor f = FunctorOfTerm(tt);
if (IsExtensionFunctor(f))
nts = nullptr;
nts = RepAppl(goal.term())+1;
} else if (IsPairTerm(tt)) {
nts = RepPair(tt);
} else {
nts = nullptr;
}
openQuery(tt, nts);
names = YAPPairTerm( TermNil );
openQuery(goal.term());
RECOVER_MACHINE_REGS();
}
YAPQuery::YAPQuery(YAPPredicate p, YAPTerm ts[]) : YAPPredicate(p.ap) {
BACKUP_MACHINE_REGS();
arity_t arity = p.ap->ArityOfPE;
if (arity) {
goal = YAPApplTerm(YAPFunctor(p.ap->FunctorOfPred), ts).term();
for (int i =0; i < arity; i++)
XREGS[i+1]=ts[i].term();
openQuery(goal.term(), nullptr);
} else {
goal = YAPAtomTerm((Atom)(p.ap->FunctorOfPred));
openQuery(goal.term(), nullptr);
}
names = TermNil;
RECOVER_MACHINE_REGS();
}
@ -833,7 +870,7 @@ void YAPEngine::doInit(YAP_file_type_t BootMode)
}
/* Begin preprocessor code */
/* live */
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "$init_system");
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "initialize_prolog");
#if __ANDROID__
Yap_AndroidBufp = (char *)malloc(Yap_AndroidMax = 4096);
Yap_AndroidBufp[0] = '\0';
@ -841,20 +878,21 @@ void YAPEngine::doInit(YAP_file_type_t BootMode)
#endif
//yerror = YAPError();
#if YAP_PYTHON
do_init_python();
#endif
YAP_Functor f = YAP_MkFunctor(YAP_LookupAtom("$init_system"), 3);
YAP_PredEntryPtr p = YAP_FunctorToPred( f );
YAP_PredEntryPtr p = YAP_AtomToPred( YAP_LookupAtom("initialize_prolog") );
YAPQuery initq = YAPQuery(YAPPredicate(p), nullptr);
if (initq.next())
{
std::cerr << "init\n" ;
initq.cut();
}
std::cerr << "cut\n" ;
}
else
{
// should throw exception
}
std::cerr << "fail\n" ;
}
}
YAPEngine::YAPEngine(int argc, char *argv[],
@ -1072,9 +1110,7 @@ YAPEngine::YAPEngine(int argc, char *argv[],
}
Term YAPEngine::top_level( std::string s)
{
/// parse string s and make term with var names
/// available.
Term tp;
@ -1083,25 +1119,26 @@ YAPEngine::YAPEngine(int argc, char *argv[],
ARG3 = MkVarTerm();
YAPPredicate p = YAPPredicate(YAP_TopGoal());
YAPQuery *Q = new YAPQuery(p,0);
Term ts[2];
ts[0]= MkAddressTerm(Q);
if (Q->next()) {
Term ts[2];
ts[0]= MkAddressTerm(Q);
ts[1]= ARG3;
return YAP_MkApplTerm(YAP_MkFunctor(YAP_LookupAtom("t"), 2), 2, ts);
} else {
ts[1] = TermNil;
}
YAPError();
return 0;
return YAP_MkApplTerm(YAP_MkFunctor(YAP_LookupAtom("t"), 2), 2, ts);
}
Term YAPEngine::next_answer(YAPQuery * &Q) {
/// parse string s and make term with var names
/// available.
Term ts[2];
ts[0]= MkAddressTerm(Q);
if (Q->next()) {
Term ts[2];
ts[0]= MkAddressTerm(Q);
ts[1]= ARG3;
return YAP_MkApplTerm(YAP_MkFunctor(YAP_LookupAtom("t"), 2), 2, ts);
ts[1] = ARG3;
} else {
ts[1] = TermNil;
}
return 0;
return YAP_MkApplTerm(YAP_MkFunctor(YAP_LookupAtom("t"), 2), 2, ts);
}

View File

@ -1,5 +1,6 @@
/**
@file yapi,hh
@file yapi.hh
@brief entry file for the YAP C++ interface
@ -18,7 +19,7 @@
* @ingroup fli_c_cx
* @defgroup yap-cplus-interface An object oriented interface for YAP.
*
* @{
* @{
*
*
* @brief C++ wrapper to terms, predicates and queries
@ -88,7 +89,7 @@ extern "C" {
#if YAP_PYTHON
#include <Python.h>
extern bool python_in_python;
#endif
}

View File

@ -58,11 +58,12 @@ class YAPQuery : public YAPPredicate
q_handles = LOCAL_CurSlot;
}
void openQuery(Term t);
void openQuery(Term t, Term *pt);
public:
YAPQuery() {
openQuery(TermTrue, nullptr);
};
/// main constructor, uses a predicate and an array of terms
///
@ -89,14 +90,24 @@ YAPQuery() {
/// goal.
inline YAPQuery(const char *s) : YAPPredicate(s, tgoal, tnames)
{
CELL *qt = nullptr;
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "got game %ld",
LOCAL_CurSlot);
if (!ap)
return;
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "%s", vnames.text());
goal = YAPTerm(tgoal);
if (IsPairTerm(tgoal)) {
qt = RepPair(tgoal);
tgoal = Yap_MkApplTerm(Yap_MkFunctor(Yap_LookupAtom("consult"), 1),1,qt);
} else if (IsApplTerm(tgoal)) {
Functor f = FunctorOfTerm(tgoal);
if (!IsExtensionFunctor(f)) {
qt = RepAppl(tgoal)+1;
}
}
names = YAPPairTerm(tnames);
openQuery(tgoal);
openQuery(tgoal, qt);
};
// inline YAPQuery() : YAPPredicate(s, tgoal, tnames)
// {
@ -113,7 +124,7 @@ YAPQuery() {
///
/// It i;
///};
YAPQuery(YAPTerm t);
/// set flags for query execution, currently only for exception handling
void setFlag(int flag) { q_flags |= flag; }
/// reset flags for query execution, currently only for exception handling
@ -383,6 +394,10 @@ public:
bool hasError() { return LOCAL_Error_TYPE != YAP_NO_ERROR; }
/// build a query on the engine
YAPQuery *query(const char *s) { return new YAPQuery(s); };
/// build a query from a term
YAPQuery *query(YAPTerm t) { return new YAPQuery(t); };
/// build a query from a Prolog term (internal)
YAPQuery *qt(Term t) { return new YAPQuery(YAPTerm(t)); };
/// current module for the engine
YAPModule currentModule() { return YAPModule(); }
/// given a handle, fetch a term from the engine

View File

@ -467,10 +467,10 @@ public:
class YAPAtomTerm : public YAPTerm {
friend class YAPModule;
// Constructor: receives a C-atom;
YAPAtomTerm(Atom a) { mk(MkAtomTerm(a)); }
YAPAtomTerm(Term t) : YAPTerm(t) { IsAtomTerm(t); }
public:
YAPAtomTerm(Atom a) { mk(MkAtomTerm(a)); }
// Constructor: receives an atom;
YAPAtomTerm(YAPAtom a) : YAPTerm() { mk(MkAtomTerm(a.a)); }
// Constructor: receives a sequence of ISO-LATIN1 codes;

View File

@ -122,7 +122,7 @@ Prop HIDDEN_PREDICATES =NULL RestoreHiddenPredicates()
// make sure we have the streams set at this point.
// don't actually want to define a field
void void Yap_InitPlIO() void
void void Yap_InitPlIO(yapi) void
union flagTerm* GLOBAL_Flags =0 void
UInt GLOBAL_flagCount Yap_InitFlags(true) RestoreFlags(GLOBAL_flagCount)

View File

@ -14,6 +14,12 @@
*************************************************************************/
/* prototype file for Yap */
/// @file Prototype Declarations
#ifndef YAP_PROTOS_H
#define YAP_PROTOS_H 1
#include "YapDefs.h"
/* absmi.c */
extern Int Yap_absmi(int);
@ -261,7 +267,7 @@ extern int Yap_locked_gcl(UInt, Int, CELL *, yamop *);
/* init.c */
extern int Yap_IsOpType(char *);
extern void Yap_InitWorkspace(UInt, UInt, UInt, UInt, UInt, int, int, int);
extern void Yap_InitWorkspace(struct yap_boot_params *, UInt, UInt, UInt, UInt, UInt, int, int, int);
extern bool Yap_AddCallToFli(struct pred_entry *pe, CPredicate call);
extern bool Yap_AddRetryToFli(struct pred_entry *pe, CPredicate re);
extern bool Yap_AddCutToFli(struct pred_entry *pe, CPredicate cut);
@ -285,7 +291,7 @@ extern void Yap_InitInlines(void);
extern int Yap_eq(Term, Term);
/* iopreds.c */
extern void Yap_InitPlIO(void);
extern void Yap_InitPlIO( struct yap_boot_params *ts );
extern void Yap_InitBackIO(void);
extern void Yap_InitIOPreds(void);
extern void Yap_DebugPlWrite(Term t);
@ -512,3 +518,5 @@ extern void init_myddas(void);
#if !HAVE_STRNCPY
#define strncpy(X, Y, Z) strcpy(X, Y)
#endif
#endif /* YAP_PROTOS_H */

View File

@ -441,67 +441,46 @@ INLINE_ONLY inline EXTERN Prop AbsValProp(ValEntry *p) { return (Prop)(p); }
don't forget to also add in qly.h
*/
/// Different predicate flags
typedef uint64_t pred_flags_t;
#define ProfiledPredFlag \
((pred_flags_t)0x2000000000) /* pred is being profiled */
#define DiscontiguousPredFlag \
((pred_flags_t)0x1000000000) /* predicates whose clauses may be all-over \
the place.. */
#define SysExportPredFlag ((pred_flags_t)0x800000000)
/* reuse export list to prolog module. */
#define NoTracePredFlag \
((pred_flags_t)0x400000000) /* cannot trace this predicate */
#define NoSpyPredFlag \
((pred_flags_t)0x200000000) /* cannot spy this predicate */
#define QuasiQuotationPredFlag \
((pred_flags_t)0x100000000) /* SWI-like quasi quotations */
#define MegaClausePredFlag \
((pred_flags_t)0x80000000) /* predicate is implemented as a mega-clause */
#define ThreadLocalPredFlag ((pred_flags_t)0x40000000) /* local to a thread */
#define MultiFileFlag ((pred_flags_t)0x20000000) /* is multi-file */
#define UserCPredFlag \
((pred_flags_t)0x10000000) /* CPred defined by the user \
*/
#define LogUpdatePredFlag \
((pred_flags_t)0x08000000) /* dynamic predicate with log. upd. sem. */
#define InUsePredFlag ((pred_flags_t)0x04000000) /* count calls to pred */
#define CountPredFlag ((pred_flags_t)0x02000000) /* count calls to pred */
#define HiddenPredFlag ((pred_flags_t)0x01000000) /* invisible predicate */
#define CArgsPredFlag \
((pred_flags_t)0x00800000) /* SWI-like C-interface pred. */
#define SourcePredFlag \
((pred_flags_t)0x00400000) /* static predicate with source declaration */
#define MetaPredFlag \
((pred_flags_t)0x00200000) /* predicate subject to a meta declaration */
#define SyncPredFlag \
((pred_flags_t)0x00100000) /* has to synch before it can execute */
#define NumberDBPredFlag \
((pred_flags_t)0x00080000) /* entry for an atom key \
*/
#define AtomDBPredFlag ((pred_flags_t)0x00040000) /* entry for a number key */
// #define GoalExPredFlag ((pred_flags_t)0x00020000) /// predicate that is
// called by goal_expand */
#define TestPredFlag ((pred_flags_t)0x00010000) /* is a test (optim. comit) */
#define AsmPredFlag ((pred_flags_t)0x00008000) /* inline */
#define StandardPredFlag ((pred_flags_t)0x00004000) /* system predicate */
#define DynamicPredFlag ((pred_flags_t)0x00002000) /* dynamic predicate */
#define CPredFlag ((pred_flags_t)0x00001000) /* written in C */
#define SafePredFlag ((pred_flags_t)0x00000800) /* does not alter arguments */
#define CompiledPredFlag ((pred_flags_t)0x00000400) /* is static */
#define IndexedPredFlag ((pred_flags_t)0x00000200) /* has indexing code */
#define SpiedPredFlag ((pred_flags_t)0x00000100) /* is a spy point */
#define BinaryPredFlag ((pred_flags_t)0x00000080) /* test predicate */
#define TabledPredFlag ((pred_flags_t)0x00000040) /* is tabled */
#define SequentialPredFlag \
((pred_flags_t)0x00000020) /* may not create parallel choice points! */
#define BackCPredFlag \
((pred_flags_t)0x00000008) /* Myddas Imported pred \
*/
#define ModuleTransparentPredFlag \
((pred_flags_t)0x00000004) /* ModuleTransparent pred */
#define SWIEnvPredFlag ((pred_flags_t)0x00000002) /* new SWI interface */
#define UDIPredFlag ((pred_flags_t)0x00000001) /* User Defined Indexing */
#define UndefPredFlag ((pred_flags_t)0x4000000000) //< Predicate not explicitely defined.
#define ProfiledPredFlag ((pred_flags_t)0x2000000000) //< pred is being profiled
#define DiscontiguousPredFlag ((pred_flags_t)0x1000000000) //< predicates whose clauses may be all-over the place..
#define SysExportPredFlag ((pred_flags_t)0x800000000) //< reuse export list to prolog module.
#define NoTracePredFlag ((pred_flags_t)0x400000000) //< cannot trace this predicate
#define NoSpyPredFlag ((pred_flags_t)0x200000000) //< cannot spy this predicate
#define QuasiQuotationPredFlag ((pred_flags_t)0x100000000) //< SWI-like quasi quotations
#define MegaClausePredFlag ((pred_flags_t)0x80000000) //< predicate is implemented as a mega-clause
#define ThreadLocalPredFlag ((pred_flags_t)0x40000000) //< local to a thread
#define MultiFileFlag ((pred_flags_t)0x20000000) //< is multi-file
#define UserCPredFlag ((pred_flags_t)0x10000000) //< CPred defined by the user
#define LogUpdatePredFlag ((pred_flags_t)0x08000000) //< dynamic predicate with log. upd. sem.
#define InUsePredFlag ((pred_flags_t)0x04000000) //< count calls to pred
#define CountPredFlag ((pred_flags_t)0x02000000) //< count calls to pred
#define HiddenPredFlag ((pred_flags_t)0x01000000) //< invisible predicate
#define CArgsPredFlag ((pred_flags_t)0x00800000) //< SWI-like C-interface pred.
#define SourcePredFlag ((pred_flags_t)0x00400000) //< static predicate with source declaration
#define MetaPredFlag ((pred_flags_t)0x00200000) //< predicate subject to a meta declaration
#define SyncPredFlag ((pred_flags_t)0x00100000) //< has to synch before it can execute
#define NumberDBPredFlag ((pred_flags_t)0x00080000) //< entry for an atom key
#define AtomDBPredFlag ((pred_flags_t)0x00040000) //< entry for a number key
// #define GoalExPredFlag ((pred_flags_t)0x00020000) /// predicate that is called by goal_expand
#define TestPredFlag ((pred_flags_t)0x00010000) //< is a test (optim. comit)
#define AsmPredFlag ((pred_flags_t)0x00008000) //< inline
#define StandardPredFlag ((pred_flags_t)0x00004000) //< system predicate
#define DynamicPredFlag ((pred_flags_t)0x00002000) //< dynamic predicate
#define CPredFlag ((pred_flags_t)0x00001000) //< written in C
#define SafePredFlag ((pred_flags_t)0x00000800) //< does not alter arguments
#define CompiledPredFlag ((pred_flags_t)0x00000400) //< is static
#define IndexedPredFlag ((pred_flags_t)0x00000200) //< has indexing code
#define SpiedPredFlag ((pred_flags_t)0x00000100) //< is a spy point
#define BinaryPredFlag ((pred_flags_t)0x00000080) //< test predicate
#define TabledPredFlag ((pred_flags_t)0x00000040) //< is tabled
#define SequentialPredFlag ((pred_flags_t)0x00000020) //< may not create parallel choice points!
#define BackCPredFlag ((pred_flags_t)0x00000008) //< Myddas Imported pred
#define ModuleTransparentPredFlag ((pred_flags_t)0x00000004)
#define SWIEnvPredFlag ((pred_flags_t)0x00000002) //< new SWI interface
#define UDIPredFlag ((pred_flags_t)0x00000001) //< User Defined Indexing
#define SystemPredFlags \
(AsmPredFlag | StandardPredFlag | CPredFlag | BinaryPredFlag | BackCPredFlag)

View File

@ -111,7 +111,7 @@
HIDDEN_PREDICATES = NULL;
Yap_InitPlIO();
Yap_InitPlIO(yapi);
GLOBAL_Flags = 0;
Yap_InitFlags(true);

391003
TAGS

File diff suppressed because one or more lines are too long

View File

@ -1,197 +0,0 @@
#!/Usr/bin/env python3
# -*- coding: utf-8 -*-
#
# YAP documentation build configuration file, created by
# sphinx-quickstart on Sun Mar 26 10:27:55 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
from recommonmark.parser import CommonMarkParser
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
'breathe'
]
breathe_projects = { "yap": "/Users/vsc/github/yap-6.3/cmake/docs/xml" }
breathe_default_project = "yap"
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
source_suffix = ['.rst', '.md']
# source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'YAP'
copyright = '2017, Vitor Santos Costa'
author = 'Vitor Santos Costa'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '6.3'
# The full version, including alpha/beta/rc tags.
release = '6.3.5'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
source_parsers = {
'.md': 'recommonmark.parser.CommonMarkParser',
}
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'YAPdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'YAP.tex', 'YAP Documentation',
'Vitor Santos Costa', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'yap', 'YAP Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'YAP', 'YAP Documentation',
author, 'YAP', 'One line description of project.',
'Miscellaneous'),
]
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}

View File

@ -1,45 +0,0 @@
.. YAP documentation master file, created by
sphinx-quickstart on Sun Mar 26 10:27:55 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to YAP's documentation!
===============================
.. doxygenindex::
.. doxygenfunction::
.. doxygenstruct::
.. doxygenenum::
.. doxygentypedef::
.. doxygenclass::
.. toctree::
:maxdepth: 2
:caption: Contents:
'../../md/attributes.md'
'../../md'/builtins.md'
'../../md'/download.md'
'../../md'/extensions.md'
'../../md'/fli.md'
'../../md'/library.md'
'../../md'/load_files.md'
'../../md'/modules.md'
'../../md'/packages.md'
'../../md'/run.md'
'../../md'/swi.md'
'../../md'/syntax.md'
'../../md'/yap.md'
'classlist.rst'
'file.rst'
'group.rst'
'section.rst'
'union.rst'
'namespace.rst'
Indices and tables
==================
* :ref:`search`

View File

@ -1,12 +0,0 @@
import sysconfig
import os.path
v = sysconfig.get_python_version()
p = sysconfig.get_config_var('LIBPL')
l = sysconfig.get_config_var('LDLIBRARY')
print(os.path.join(p,l))
p = sysconfig.get_config_var('DESTDIR')
n = '../libpython3.6m.dylib'
l = os.path.join(p,n)
print(l)

View File

@ -1,31 +0,0 @@
/* Define to 1 if you have the <openssl/ripemd.h> header file. */
#ifndef HAVE_APACHE2_UTIL_MD5_H
/* #undef HAVE_APACHE2_UTIL_MD5_H */
#endif
/* Define to 1 if you have the <openssl/ripemd.h> header file. */
#ifndef HAVE_APR_1_APR_MD5_H
/* #undef HAVE_APR_1_APR_MD5_H */
#endif
/* Define to 1 if you have the <openssl/md5.h> header file. */
#ifndef HAVE_OPENSSL_MD5_H
/* #undef HAVE_OPENSSL_MD5_H */
#endif
/* Define to 1 if you have the <openssl/ripemd.h> header file. */
#ifndef HAVE_OPENSSL_RIPEMD_H
/* #undef HAVE_OPENSSL_RIPEMD_H */
#endif
/* "Define if you have the crypt function." */
#ifndef HAVE_CRYPT
/* #undef HAVE_CRYPT */
#endif
/* Define to 1 if you have the <crypt.h> header file. */
#ifndef HAVE_CRYPT_H
/* #undef HAVE_CRYPT_H */
#endif

View File

@ -1,2 +0,0 @@
#define HAVE_RAPTOR2_RAPTOR2_H 1
/* #undef HAVE_RAPTOR_H */

View File

@ -1,26 +0,0 @@
/*--------------------------------------------------------------------------
* This file is autogenerated from rconfig.h.cmake
* during the cmake configuration of your project. If you need to make changes
* edit the original file NOT THIS FILE.
* --------------------------------------------------------------------------*/
#ifndef RCONFIG_H
#define RCONFIG_H
/* Define to 1 if you have the <alloca.h> header file. */
#ifndef HAVE_R_H
#define HAVE_R_H 1
#endif
/* Define to 1 if you have the <alloca.h> header file. */
#ifndef HAVE_R_EMBEDDED_H
#define HAVE_R_EMBEDDED_H 1
#endif
/* Define to 1 if you have the <alloca.h> header file. */
#ifndef HAVE_R_INTERFACE_H
#define HAVE_R_INTERFACE_H 1
#endif
#endif

View File

@ -53,7 +53,7 @@ typedef enum vfs_flags {
VFS_CAN_SEEK = 0x4, /// we can seek within files in this space
VFS_HAS_PREFIX = 0x8, /// has a prefix that identifies a file in this space
VFS_HAS_SUFFIX = 0x10, /// has a suffix that describes the file.
VFS_HAS_FUNCTION = 0x10, /// has a suffix that describes the file.
VFS_HAS_FUNCTION = 0x20 /// has a suffix that describes the file.
} vfs_flags_t;
typedef union {
@ -76,34 +76,29 @@ typedef struct vfs {
const char *suffix;
bool (*id)(struct vfs *me, const char *s);
/** operations */
bool (*open)(struct vfs *me, struct stream_desc *st, const char *s,
const char *io_mode);
; /// open an object
void *(*open)(const char *s,
const char *io_mode); /// open an object
/// in this space, usual w,r,a,b flags plus B (store in a buffer)
bool (*close)(struct stream_desc *stream); /// close the object
int (*get_char)(struct stream_desc *stream); /// get an octet to the stream
int (*putc)(int ch,
struct stream_desc *stream); /// output an octet to the stream
int64_t (*seek)(struct stream_desc *stream, int64_t offset,
bool (*close)(int sno); /// close the object
int (*get_char)(int sno); /// get an octet to the stream
int (*put_char)(int sno, wchar_t ch); /// output an octet to the stream
void (*flush)(int sno); /// flush a stream
int64_t (*seek)(int sno, int64_t offset,
int whence); /// jump around the stream
void *(*opendir)(struct vfs *me,
const char *s); /// open a directory object, if one exists
const char *(*nextdir)(
void *d); /// walk to the next entry in a directory object
void *(*opendir)(const char *s); /// open a directory object, if one exists
const char *(*nextdir)(void *d); /// walk to the next entry in a directory object
void (*closedir)(void *d);
; /// close access a directory object
bool (*stat)(struct vfs *me, const char *s,
bool (*stat)(const char *s,
vfs_stat *); /// obtain size, age, permissions of a file.
bool (*isdir)(struct vfs *me, const char *s); /// verify whether is directory.
bool (*exists)(struct vfs *me,
const char *s); /// verify whether a file exists.
bool (*chdir)(struct vfs *me,
const char *s); /// set working directory (may be virtual).
encoding_t enc; /// how the file is encoded.
YAP_Term (*parsers)(void *stream); // a set of parsers that can read the
bool (*isdir)(const char *s); /// verify whether is directory.
bool (*exists)(const char *s); /// verify whether a file exists.
bool (*chdir)(const char *s); /// set working directory (may be virtual).
encoding_t enc; /// default file encoded.
YAP_Term (*parsers)(int sno); // a set of parsers that can read the
// stream and generate a YAP_Term
int (*writers)(int ch, void *stream);
; /// convert a YAP_Term into this space
int (*writers)(int ch, int sno );
/// convert a YAP_Term into this space
const char *virtual_cwd;
/** VFS dep
endent area */
@ -114,16 +109,14 @@ typedef struct vfs {
extern VFS_t *GLOBAL_VFS;
static inline VFS_t *vfs_owner(const char *fname) {
return NULL;
VFS_t *me = GLOBAL_VFS;
int d;
size_t sz0 = strlen(fname);
size_t sz0 = strlen(fname), sz;
while (me) {
if (me->vflags & VFS_HAS_PREFIX && strstr(fname, me->prefix))
if ((me->vflags & VFS_HAS_PREFIX) && strstr(fname, me->prefix) == fname)
return me;
size_t sz = strlen(me->suffix);
if (me->vflags & VFS_HAS_SUFFIX && (d = (sz0 - sz)) >= 0 &&
if (me->vflags & VFS_HAS_SUFFIX && (sz = strlen(me->suffix)) && (d = (sz0 - sz)) >= 0 &&
strcmp(fname + d, me->suffix) == 0)
return me;
if (me->vflags & VFS_HAS_FUNCTION && (me->id(me, fname))) {

View File

@ -225,75 +225,76 @@ typedef enum {
#define YAP_BOOT_MODE 2
typedef struct yap_boot_params {
//> boot type as suggested by the user
//> boot type as suggested by the user
YAP_file_type_t boot_file_type;
//> if NON-NULL, path where we can find the saved state
//> if NON-NULL, path where we can find the saved state
const char *SavedState;
//> if NON-0, minimal size for Heap or Code Area
//> if NON-0, minimal size for Heap or Code Area
size_t HeapSize;
//> if NON-0, maximal size for Heap or Code Area
//> if NON-0, maximal size for Heap or Code Area
size_t MaxHeapSize;
//> if NON-0, minimal size for Local+Global Stack
//> if NON-0, minimal size for Local+Global Stack
size_t StackSize;
//> if NON-0, maximal size for Local+Global Stack
//> if NON-0, maximal size for Local+Global Stack
size_t MaxStackSize;
//*> deprecated
size_t MaxGlobalSize;
//> if NON-0, minimal size for Trail
//> if NON-0, minimal size for Trail
size_t TrailSize;
//> if NON-0, maximal size for Trail
size_t MaxTrailSize;
//> if NON-0, minimal size for AttributeVarStack
//> if NON-0, minimal size for AttributeVarStack
size_t AttsSize;
//> if NON-0, maximal size for AttributeVarStack
//> if NON-0, maximal size for AttributeVarStack
size_t MaxAttsSize;
//> if NON-NULL, value for YAPLIBDIR
//> if NON-NULL, value for YAPLIBDIR
const char *YapLibDir;
//> if NON-NULL, value for YAPSSHAREDIR, that is, default value for libraries
//> if NON-NULL, value for YAPSSHAREDIR, that is, default value for libraries
const char *YapShareDir;
//> if NON-NULL, name for a Prolog file to use when booting
//> if NON-NULL, name for a Prolog file to use when booting
const char *YapPrologBootFile;
//> if NON-NULL, name for a Prolog file to use when initializing
//> if NON-NULL, name for a Prolog file to use when initializing
const char *YapPrologInitGoal;
//> if NON-NULL, name for a Prolog file to consult before entering top-level
//> if NON-NULL, name for a Prolog file to consult before entering top-level
const char *YapPrologRCFile;
//> if NON-NULL, a goal to run before top-level
//> if NON-NULL, a goal to run before top-level
const char *YapPrologGoal;
//> if NON-NULL, a goal to run as top-level
//> if NON-NULL, a goal to run as top-level
const char *YapPrologTopLevelGoal;
//> if NON-NULL, a path to extend file-search-path
//> if NON-NULL, a path to extend file-search-path
const char *YapPrologAddPath;
//> if previous NON-NULL and TRUE, halt after consulting that file
//> if previous NON-NULL and TRUE, halt after consulting that file
bool HaltAfterConsult;
//> ignore .yaprc, .prolog.ini, etc. files.
//> ignore .yaprc, .prolog.ini, etc. files.
bool FastBoot;
//> the next field only interest YAPTAB
//> if NON-0, maximum size for Table Space
//> the next field only interest YAPTAB
//> if NON-0, maximum size for Table Space
size_t MaxTableSpaceSize;
/* the next three fields only interest YAPOR, but we keep them so that
users don't need to recompile DLL in order to use YAPOR */
//> if NON-0, number of workers we want to have (default=1)
//> if NON-0, number of workers we want to have (default=1)
unsigned long int NumberWorkers;
//> if NON-0, manage the inner scheduler loop (default = 10)
//> if NON-0, manage the inner scheduler loop (default = 10)
unsigned long int SchedulerLoop;
//> if NON-0, say how long to keep nodes (default = 3)
//> if NON-0, say how long to keep nodes (default = 3)
unsigned long int DelayedReleaseLoad;
//> end of YAPOR fields
//> end of YAPOR fields
/* whether Prolog should handle interrupts. Note that
interrupts will always be disabled in embedded mode. */
bool PrologCannotHandleInterrupts;
//> flag for JIT mode
//> flag for JIT mode
int ExecutionMode;
//> number of arguments that Prolog will see
//> number of arguments that Prolog will see
int Argc;
//> array of arguments as seen by Prolog
//> array of arguments as seen by Prolog
char **Argv;
//> embedded in some other system: no signals, readline, etc
//> embedded in some other system: no signals, readline, etc
bool Embedded;
//> QuietMode
//> QuietMode
int QuietMode;
/* nf: Begin ypp preprocessor code */
//> 0, maintain default, > 0 use fd-1, < 0 close
int inp, out, err;
/* support nf's ypp preprocessor code */
#define YAP_MAX_YPP_DEFS 100
char *def_var[YAP_MAX_YPP_DEFS];
char *def_value[YAP_MAX_YPP_DEFS];
@ -301,9 +302,9 @@ typedef struct yap_boot_params {
/* End preprocessor code */
#ifdef MYDDAS_MYSQL
//> If any myddas option was given
//> If any myddas option was given
short myddas;
//> MYDDAS Fields
//> MYDDAS Fields
char *myddas_user;
char *myddas_pass;
char *myddas_db;
@ -311,7 +312,7 @@ typedef struct yap_boot_params {
#endif
/* errornumber */
int ErrorNo;
//> errorstring
//> errorstring
char *ErrorCause;
} YAP_init_args;

View File

@ -676,6 +676,8 @@ extern X_API int YAP_RequiresExtraStack(size_t);
extern X_API YAP_file_type_t YAP_parse_yap_arguments(int argc, char *argv[],
YAP_init_args *iap);
extern X_API void *YAP_foreign_stream(int sno);
extern X_API YAP_Int YAP_AtomToInt(YAP_Atom At);
extern X_API YAP_Atom YAP_IntToAtom(YAP_Int i);

View File

@ -229,6 +229,7 @@ typedef struct stream_desc {
struct {
const unsigned char *buf, *ptr;
} irl;
void *private_data;
} u;
YAP_Int charcount, linecount, linepos;

View File

@ -246,6 +246,13 @@ static void unix_upd_stream_info(StreamDesc *s) {
void Yap_DefaultStreamOps(StreamDesc *st) {
CACHE_REGS
if (st->vfs) {
st->stream_wputc = st->vfs->put_char;
st->stream_wgetc = st->vfs->get_char;
st->stream_putc = FilePutc;
st->stream_getc = PlGetc;
return;
}
st->stream_wputc = put_wchar;
st->stream_wgetc = get_wchar_UTF8;
st->stream_putc = FilePutc;
@ -1281,15 +1288,21 @@ do_open(Term file_name, Term t2,
if (st - GLOBAL_Stream < 3) {
flags |= RepError_Prolog_f;
}
if ((fd = fopen(fname, io_mode)) == NULL ||
st->vfs = NULL;
if ((st->vfs = vfs_owner(fname)) != NULL) {
st->u.private_data = st->vfs->open(fname, io_mode);
fd = NULL;
if (st->u.private_data == NULL)
return (PlIOError(EXISTENCE_ERROR_SOURCE_SINK, file_name, "%s", fname));
} else if ((fd = fopen(fname, io_mode)) == NULL ||
(!(flags & Binary_Stream_f) && binary_file(fname))) {
strncpy(LOCAL_FileNameBuf, fname, MAXPATHLEN);
if (fname != fbuf)
freeBuffer((void *)fname);
fname = LOCAL_FileNameBuf;
UNLOCK(st->streamlock);
if (errno == ENOENT) {
free(args);
free(args);
if (errno == ENOENT && !strchr(io_mode,'r')) {
return (PlIOError(EXISTENCE_ERROR_SOURCE_SINK, file_name, "%s: %s", fname,
strerror(errno)));
} else {
@ -1829,12 +1842,28 @@ static Int get_abs_file_parameter(USES_REGS1) {
Yap_Error(DOMAIN_ERROR_ABSOLUTE_FILE_NAME_OPTION, ARG1, NULL);
return false;
}
void Yap_InitPlIO(void) {
void Yap_InitPlIO(struct yap_boot_params *argi) {
Int i;
Yap_stdin = stdin;
if (argi->inp >0 )
Yap_stdin = fdopen(argi->inp-1, "r");
else if (argi->inp)
Yap_stdin = NULL;
else
Yap_stdin = stdin;
if (argi->out >0 )
Yap_stdout = fdopen(argi->out-1, "a");
else if (argi->out)
Yap_stdout = NULL;
else
Yap_stdout = stdout;
Yap_stderr = stderr;
if (argi->err >0 )
Yap_stderr = fdopen(argi->err-1, "a");
else if (argi->out)
Yap_stdout = NULL;
else
Yap_stderr = stderr;
GLOBAL_Stream =
(StreamDesc *)Yap_AllocCodeSpace(sizeof(StreamDesc) * MaxStreams);
for (i = 0; i < MaxStreams; ++i) {

View File

@ -79,7 +79,7 @@ static bool is_directory(const char *FileName) {
VFS_t *vfs;
if ((vfs = vfs_owner(FileName))) {
return vfs->isdir(vfs, FileName);
return vfs->isdir(FileName);
}
#ifdef _WIN32
DWORD dwAtts = GetFileAttributes(FileName);
@ -105,7 +105,7 @@ bool Yap_Exists(const char *f) {
VFS_t *vfs;
if ((vfs = vfs_owner(f))) {
return vfs->exists(vfs, f);
return vfs->exists(f);
}
#if _WIN32
if (_access(f, 0) == 0)
@ -348,7 +348,7 @@ static bool ChDir(const char *path) {
VFS_t *v;
if ((v = vfs_owner(path))) {
return v->chdir(v, path);
return v->chdir(path);
}
#if _WIN32
rc = true;

View File

@ -31,7 +31,7 @@
install(TARGETS Yapmysql
RUNTIME DESTINATION ${dlls}
ARCHIVE DESTINATION ${dlls}
LIBRARY DESTINATION ${libdir}
LIBRARY DESTINATION ${dlls}
)
endif()
include_directories(${MYSQL_INCLUDE_DIR} ..)

View File

@ -32,7 +32,7 @@ set_property(GLOBAL APPEND PROPERTY COMPILE_DEFINITIONS
-DMYDDAS_POSTGRES=1)
install(TARGETS Yappostgres
LIBRARY DESTINATION ${libdir}
LIBRARY DESTINATION ${dlls}
RUNTIME DESTINATION ${dlls}
ARCHIVE DESTINATION ${dlls}
)

View File

@ -32,8 +32,8 @@ IF(WIN32)
ARCHIVE DESTINATION ${libdir} )
else()
install(TARGETS YAPPython
LIBRARY DESTINATION ${libdir}
RUNTIME DESTINATION ${libdir}
ARCHIVE DESTINATION ${libdir} )
LIBRARY DESTINATION ${dlls}
RUNTIME DESTINATION ${dlls}
ARCHIVE DESTINATION ${dlls} )
endif()

View File

@ -18,6 +18,51 @@ void YEM(const char *exp, int line, const char *file, const char *code)
fprintf(stderr, "**** Warning,%s@%s:%d: failed while executing %s\n", code, file, line, exp);
}
static PyObject *s_to_python( const char *s, bool eval, PyObject *p0)
{
PyObject *o;
if (eval)
{
o = PythonLookup(s,p0);
/* if (!o)
return o;
*/
}
else
{
o = PythonLookupSpecial(s);
}
if (o)
{
Py_INCREF(o);
return CHECKNULL(YAP_MkStringTerm(s), o);
} else {
PyObject *pobj = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
return pobj;
}
}
/**
* obtain the object matching a certain string.
*
* @param t handle to Prolog term
* @param t whether should try to evaluate evaluables.
*
* @return a Python object descriptor or NULL if failed
*/
X_API PyObject *string_to_python( const char *s, bool eval, PyObject *p0)
{
char *buf = malloc(strlen(s)+1), *child;
while((child = strchr(s,'.')) != NULL ) {
size_t len = child - s;
strncpy(buf,s,len);
buf[len]='\0';
p0 = s_to_python(buf, eval, p0);
s = child+1;
}
return s_to_python(s, eval, p0);
}
/**
* term_to_python translates and evaluates from Prolog to Python
*

View File

@ -15,7 +15,7 @@
static PyObject *finalLookup(PyObject *i, const char *s) {
PyObject *rc;
if (i == NULL)
return Py_None;
return NULL;
if (strcmp(s,"none") == 0)
return Py_None;
if (PyDict_Check(i)) {
@ -34,7 +34,7 @@ static PyObject *finalLookup(PyObject *i, const char *s) {
PyObject *PythonLookupSpecial(const char *s) {
if (s == NULL)
return Py_None;
return NULL;
if (strcmp(s, "true") == 0) {
return Py_True;
}
@ -52,9 +52,9 @@ PyObject *PythonLookupSpecial(const char *s) {
}
PyObject *lookupPySymbol(const char *sp, PyObject *pContext, PyObject **duc) {
PyObject *out = Py_None;
PyObject *out = NULL;
if (!sp)
return Py_None;
return NULL;
if ((out = finalLookup(pContext, sp))) {
return out;
}
@ -66,54 +66,32 @@ PyObject *lookupPySymbol(const char *sp, PyObject *pContext, PyObject **duc) {
return out;
}
PyObject *py_Local = PyEval_GetLocals();
if ((out = finalLookup(py_Local, sp))) {
if ((out = finalLookup(py_Local, sp)) && out != Py_None) {
return out;
}
PyObject *py_Global = PyEval_GetGlobals();
if ((out = finalLookup(py_Global, sp))) {
if ((out = finalLookup(py_Global, sp)) ) {
return out;
}
if ((out = finalLookup(py_ModDict, sp))) {
return out;
}
if ((out = finalLookup(py_Main, sp))) {
if ((out = finalLookup(py_Main, sp)) ) {
return out;
}
return Py_None;
}
int lookupPyModule(Py_mod *q) {
char buf[1024], *S = buf;
int prefix = 0;
int j;
py_ModDict = PyObject_GetAttrString(py_Sys, "modules");
PyObject *ob;
S[0] = '\0';
while (YAP_IsAtomTerm(q->names[prefix])) {
strcat(S, YAP_AtomName(YAP_AtomOfTerm(q->names[prefix])));
strcat(S, ".");
S += strlen(S);
prefix++;
}
for (j = prefix; j > 0; j--) {
S = strrchr(buf, '.');
S[0] = '\0';
if ((ob = PyDict_GetItemString(py_ModDict, buf)) != NULL &&
PyModule_Check(ob)) {
Py_INCREF(ob);
q->mod = ob;
return j;
}
}
return 0;
return NULL;
}
PyObject *PythonLookup(const char *s, PyObject *oo) {
PyObject *o;
if ((o = PythonLookupSpecial(s)))
return o;
return lookupPySymbol(s, oo, NULL);
if ((o = lookupPySymbol(s, oo, NULL)) == NULL)
return NULL;
else {
Py_INCREF(o);
return o;
}
}
PyObject *find_obj(PyObject *ob, term_t l, bool eval) {

View File

@ -629,16 +629,15 @@ PyThreadState *tstate;
static YAP_Int p_python_threaded(void) {
PyErr_Clear();
PyRun_SimpleString("print( \"thread initiated\" )");
// PyEval_ReleaseThread(tstate);
_threaded = true;
// _threaded = true;
// _locked = 0;
pyErrorAndReturn(true, false);
}
static PyGILState_STATE gstate;
term_t python_acquire_GIL(void) {
term_t python_acquire_GIL(void) {
term_t curSlot = 1; //PL_new_term_ref();
if (!_threaded)
pyErrorAndReturn(curSlot, false);

View File

@ -1,5 +1,7 @@
#include "python.h"
#include <YapStreams.h>
#include <VFS.h>
atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
ATOM_comma, ATOM_builtin, ATOM_A, ATOM_V, ATOM_self, ATOM_nil, ATOM_brackets, ATOM_curly_brackets;
@ -19,6 +21,88 @@ X_API PyObject *py_Sys;
PyObject *py_Context;
PyObject *py_ModDict;
VFS_t pystream;
static void *
py_open( const char *name, const char *io_mode) {
if (strcasestr(name,"//python/")== name)
name += strlen("//python/");
// we assume object is already open, so there is no need to open it.
PyObject *stream = string_to_python( name, true, NULL);
if (stream == Py_None)
return NULL;
return stream;
}
static bool
py_close(int sno) {
PyObject *s = YAP_foreign_stream(sno);
PyObject* fclose = PyObject_GetAttrString(s, "close");
PyObject* rc= PyObject_CallObject(fclose, NULL);
bool v = (rc == Py_True);
return v;
}
static PyObject * pyw; // buffer
static int pyw_kind;
PyObject * pyw_data;
static int
py_put(int sno, int ch) {
PyObject *s = YAP_foreign_stream(sno);
PyUnicode_WRITE( pyw_kind, pyw_data, 0, ch );
PyObject* fput = PyObject_GetAttrString(s, "write");
PyObject_CallFunctionObjArgs(fput, pyw, NULL);
return ch;
}
static int
py_get(int sno) {
PyObject *s = YAP_foreign_stream(sno);
PyObject* fget = PyObject_GetAttrString(s, "read");
PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL);
return PyUnicode_READ_CHAR( pyr, 0) ;
}
static int64_t py_seek(int sno, int64_t where, int how) {
PyObject *s = YAP_foreign_stream(sno);
PyObject* fseek = PyObject_GetAttrString(s, "seek");
PyObject *pyr = PyObject_CallFunctionObjArgs(fseek, PyLong_FromLong(where), PyLong_FromLong(how), NULL);
return PyLong_AsLong(pyr);
}
static void
py_flush(int sno) {
PyObject *s = YAP_foreign_stream(sno);
PyObject* flush = PyObject_GetAttrString(s, "flush");
PyObject_CallFunction( flush, NULL);
}
static bool
init_python_stream(void)
{
pyw = PyUnicode_FromString("x");
pyw_kind = PyUnicode_KIND(pyw);
pyw_data = PyUnicode_DATA(pyw);
pystream.name = "python stream";
pystream.vflags = VFS_CAN_WRITE|VFS_CAN_EXEC| VFS_CAN_SEEK|VFS_HAS_PREFIX;
pystream.prefix = "//python/";
pystream.suffix = NULL;
pystream.open = py_open;
pystream.close = py_close;
pystream.get_char = py_get;
pystream.put_char = py_put;
pystream.flush = py_flush;
pystream.seek = py_seek;
pystream.next = GLOBAL_VFS;
GLOBAL_VFS = &pystream;
// NULL;
return true;
}
X_API PyObject *py_F2P;
bool python_in_python;
@ -38,8 +122,10 @@ static void add_modules(void) {
Py_INCREF(py_Yapex);
//py_F2P = PyObject_GetAttrString(py_Yap, "globals");
py_F2P = NULL;
init_python_stream();
}
static void install_py_constants(void) {
FUNCTOR_dot2 = PL_new_functor(PL_new_atom("."), 2);
// FUNCTOR_equal2 = PL_new_functor(PL_new_atom("="), 2);

View File

@ -44,7 +44,7 @@ typedef struct s_mod_t {
extern X_API YAP_Term pythonToYAP(PyObject *pVal);
extern X_API PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o);
extern X_API PyObject *string_to_python( const char *s, bool eval, PyObject *p0);
typedef YAP_Arity arity_t;
extern atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
@ -175,7 +175,6 @@ extern bool python_asign(term_t t, PyObject *exp, PyObject *context);
extern foreign_t python_builtin(term_t out);
extern int lookupPyModule(Py_mod *q);
extern PyObject *lookupPySymbol(const char *s, PyObject *q, PyObject **d);
extern install_t install_pypreds(void);

View File

@ -109,7 +109,6 @@ Data types are
*************************************************************************************************************/
:- use_module(library(shlib)).
:- use_module(library(lists)).
:- use_module(library(apply_macros)).
:- use_module(library(charsio)).
@ -153,5 +152,3 @@ add_cwd_to_python :-
% done
:- initialization( load_foreign_files([libYAPPython], [], init_python), now ).
:- initialization( load_foreign_library(foreign(libYAPPython), init_python), now ).

View File

@ -72,13 +72,17 @@ add_custom_target( YAP4PY ALL
COMMAND ${CMAKE_COMMAND} -E copy ${pl_os_library} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog/os
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/setup.py sdist bdist_wheel
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS STARTUP ${dlls} ${PYTHON_SOURCES} ${PROLOG_SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/setup.py ${SWIG_MODULE_Py2YAP_REAL_NAME} )
DEPENDS STARTUP ${dlls} ${PYTHON_SOURCES} ${PROLOG_SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/setup.py ${SWIG_MODULE_Py2YAP_REAL_NAME} )
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --no-index -f dist yap4py
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --force --no-index -f dist yap4py
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})"
DEPENDS Py4YAP ${CMAKE_BINARY_DIR}/${YAP_STARTUP} ${dlls} )
install(FILES yapi.yap DESTINATION ${libpl})
if (WITH_DOCS AND DOXYGEN_FOUND)

View File

@ -1,13 +1,26 @@
%% @file yapi.yap
%% @brief support yap shell
%%
:- module(yapi, [query/3]).
:- module(yapi, [python_query/2,
python_ouput/0,
yap_query/3]).
:- use_module( library(lists) ).
:- use_module( library(maplist) ).
:- use_module( library(rbtrees) ).
%% @pred yap_query(0:Goal, + VarList, +OutStream, - Dictionary)
%% @pred yap_query(0:Goal, + VarList, - Dictionary)
%%
%% dictionary, Examples
%%
%%
python_query( Engine, String ) :-
atomic_to_term( String, Goal, VarNames ), writeln(Goal),
yap_query( Goal, VarNames, user_error, Dict), writeln(Dict),
Engine.bindings := Dict.
%% @pred yap_query(0:Goal, + VarList, +OutStream, - Dictionary)
%% @pred yap_query(0:Goal, + VarList, - Dictionary)
%%
@ -24,8 +37,10 @@ yap_query( Goal, VarNames, Stream, Dictionary) :-
prolog:yap_query( Goal, VarNames, Dictionary) :-
yap_query( Goal, VarNames, user_output, Dictionary).
constraints(QVs, Goal, Stream, {Dict}) :-
constraints(QVs0, Goal0, Stream, {Dict}) :-
!,
copy_term(Goal0+QVs0, Goal+QVs),
writeln(ivs-IVs),
term_variables(Goal, IVs),
foldl(enumerate, IVs, 0, _Ns),
out(QVs, Stream, Dict).
@ -43,7 +58,8 @@ enumerate('$VAR'(A), I, I1) :-
enum(I, [C]) :-
I < 26,
!, C is "A" + I.
!,
C is "A" + I.
enum(I, [C|Cs]) :-
J is I//26,
K is I mod 26,
@ -63,14 +79,24 @@ v2py(v(I0) = v(I0), I0, I) :-
I is I0+1.
output([V=B], S) :-
format(S, 'a = ~q~n', [V, B]).
!,
format(S, '~a = ~q~n', [V, B]).
output([V=B|Ns], S) :-
format( S, 'a = ~q.~n', [V, B]),
format( S, '~a = ~q.~n', [V, B]),
output( Ns, S).
bvs([V=B],{V:B}) :-
!.
bvs([V=B|Ns], (V:B,N)) :-
output( Ns, N).
:- start_low_level_trace.
bvs([V=B], S:B) :-
atring_to_atom(V,S),
!.
bvs([V=B|Ns], (S:B,N) ) :-
atring_to_atom(V,S),
output( Ns, N).
python_output :-
:= import(sys),
open('//python/sys.stdout', append, Output),
open('//python/sys.stderr', append, Error),
set_prolog_flag(user_output, Output),
set_prolog_flag(user_error, Error).

View File

@ -1,78 +1,72 @@
set (EXTRAS
MANIFEST.in
YAP_KERNEL.md
)
set (EXTRAS
MANIFEST.in
YAP_KERNEL.md
)
set (PYTHON_SOURCES
yap_kernel_launcher.py
data_kernelspec/kernel.json
yap_kernel/__init__.py
yap_kernel/__main__.py
yap_kernel/_version.py
yap_kernel/codeutil.py
yap_kernel/connect.py
yap_kernel/datapub.py
yap_kernel/displayhook.py
yap_kernel/embed.py
yap_kernel/eventloops.py
yap_kernel/heartbeat.py
yap_kernel/interactiveshell.py
yap_kernel/iostream.py
yap_kernel/jsonutil.py
yap_kernel/kernelapp.py
yap_kernel/kernelbase.py
yap_kernel/kernelspec.py
yap_kernel/log.py
yap_kernel/parentpoller.py
yap_kernel/pickleutil.py
yap_kernel/serialize.py
yap_kernel/yapkernel.py
yap_kernel/zmqshell.py
yap_kernel/comm/__init__.py
yap_kernel/comm/comm.py
yap_kernel/comm/manager.py
yap_kernel/gui/__init__.py
yap_kernel/gui/gtk3embed.py
yap_kernel/gui/gtkembed.py
yap_kernel/inprocess/__init__.py
yap_kernel/inprocess/blocking.py
yap_kernel/inprocess/channels.py
yap_kernel/inprocess/client.py
yap_kernel/inprocess/constants.py
yap_kernel/inprocess/ipkernel.py
yap_kernel/inprocess/manager.py
yap_kernel/inprocess/socket.py
yap_kernel/pylab/__init__.py
yap_kernel/pylab/backend_inline.py
yap_kernel/pylab/config.py
)
set (PYTHON_SOURCES
yap_kernel_launcher.py
data_kernelspec/kernel.json
yap_kernel/__init__.py
yap_kernel/__main__.py
yap_kernel/_version.py
yap_kernel/codeutil.py
yap_kernel/connect.py
yap_kernel/datapub.py
yap_kernel/displayhook.py
yap_kernel/embed.py
yap_kernel/eventloops.py
yap_kernel/heartbeat.py
yap_kernel/interactiveshell.py
yap_kernel/iostream.py
yap_kernel/jsonutil.py
yap_kernel/kernelapp.py
yap_kernel/kernelbase.py
yap_kernel/kernelspec.py
yap_kernel/log.py
yap_kernel/parentpoller.py
yap_kernel/pickleutil.py
yap_kernel/serialize.py
yap_kernel/yapkernel.py
yap_kernel/zmqshell.py
yap_kernel/comm/__init__.py
yap_kernel/comm/comm.py
yap_kernel/comm/manager.py
yap_kernel/gui/__init__.py
yap_kernel/gui/gtk3embed.py
yap_kernel/gui/gtkembed.py
yap_kernel/inprocess/__init__.py
yap_kernel/inprocess/blocking.py
yap_kernel/inprocess/channels.py
yap_kernel/inprocess/client.py
yap_kernel/inprocess/ipkernel.py
yap_kernel/inprocess/manager.py
yap_kernel/inprocess/socket.py
yap_kernel/pylab/__init__.py
yap_kernel/pylab/backend_inline.py
yap_kernel/pylab/config.py
)
foreach(i ${PYTHON_SOURCES})
configure_file(${i} ${CMAKE_CURRENT_BINARY_DIR}/${i})
endforeach()
configure_file("setup.py" ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
configure_file("MANIFEST.in" ${CMAKE_CURRENT_BINARY_DIR}/MANIFEST.in)
configure_file("YAP_KERNEL.md" ${CMAKE_CURRENT_BINARY_DIR}/README)
configure_file("yap_kernel/_version.py" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/_version.py )
configure_file("${CMAKE_SOURCE_DIR}/docs/icons/yap_32x32x32.png" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png)
configure_file("${CMAKE_SOURCE_DIR}/docs/icons/yap_64x64x32.png" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-64x64.png)
configure_file("${CMAKE_SOURCE_DIR}/misc/editors/prolog.js" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/prolog.js)
configure_file(setup.py.in ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources)
file(COPY yap_kernel DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
file( COPY MANIFEST.in setup.cfg data_kernelspec yap_kernel_launcher.py DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
# file( GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/README.md INPUT YAP_KERNEL.md )
file( COPY yap_kernel/_version.py DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel )
file( GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png INPUT ${CMAKE_SOURCE_DIR}/docs/icons/yap_32x32x32.png )
file( GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-64x64.png INPUT ${CMAKE_SOURCE_DIR}/docs/icons/yap_64x64x32.png )
file( COPY ${CMAKE_SOURCE_DIR}/misc/editors/prolog.js DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/)
set(SETUP_PY "${CMAKE_CURRENT_BINARY_DIR}/setup.py")
set( PYTHON_INSTALL sdist bdist_wheel)
set(SETUP_PY ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
add_custom_target( YAPKernel ALL
add_custom_target( YAPKernel ALL
COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} sdist
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
)
COMMAND ${PYTHON_EXECUTABLE} setup.py clean sdist bdist_wheel
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS libYap ${SWIG_MODULE_Py2YAP_REAL_NAME}
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --no-index -f dist yap_kernel
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})")
)
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --no-index -f dist yap_kernel")
install(FILES jupyter.yap
DESTINATION ${libpl}
)
# install(FILES jupyter.yap
# DESTINATION ${libpl} )

View File

@ -14,10 +14,11 @@ name = 'yap_kernel'
#-----------------------------------------------------------------------------
import sys
import setuptools
v = sys.version_info
if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)):
error = "ERROR: %s requires Python version 2.7 or 3.3 or above." % name
error = "ERROR: %s requires Python version 3.3 or above." % name
print(error, file=sys.stderr)
sys.exit(1)
@ -34,23 +35,26 @@ import shutil
from distutils.core import setup
pjoin = os.path.join
here = os.path.relpath(os.path.dirname(__file__))
pkg_root = pjoin(here, name)
here = os.path.abspath(os.path.dirname(__file__))
# pkg_root = pjoin(here, name)
packages = []
for d, _, _ in os.walk(pjoin(here, name)):
if os.path.exists(pjoin(d, '__init__.py')):
packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
packages = setuptools.find_packages('${CMAKE_CURRENT_SOURCE_DIR}')
# for d, _, _ in os.walk(pjoin(here, name)):
# if os.path.exists(pjoin(d, '__init__.py')):
# packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
package_data = {
'ipykernel': ['resources/*.*'],
'yap_kernel': ['resources/*.*'],
}
version_ns = {}
with open(pjoin(here, name, '_version.py')) as f:
with open(pjoin('${CMAKE_CURRENT_SOURCE_DIR}', name, '_version.py')) as f:
exec(f.read(), {}, version_ns)
setup_args = dict(
name = name,
version = version_ns['__version__'],
@ -59,8 +63,8 @@ setup_args = dict(
py_modules = ['yap_kernel_launcher'],
package_data = package_data,
description = "YAP Kernel for Jupyter",
author = 'IPython Development Team and Vitor Santos Costa',
author_email = 'vsc@dcc.fc.up.ot',
author = 'YP Development Team',
author_email = 'YAP-dev@scipy.org',
url = 'http://ipython.org',
license = 'BSD',
platforms = "Linux, Mac OS X, Windows",
@ -70,8 +74,8 @@ setup_args = dict(
'Intended Audience :: System Administrators',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Prolog',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
)
@ -85,7 +89,6 @@ install_requires = setuptools_args['install_requires'] = [
'traitlets>=4.1.0',
'jupyter_client',
'tornado>=4.0',
'yap4py'
]
if any(a.startswith(('bdist', 'build', 'install')) for a in sys.argv):
@ -101,10 +104,6 @@ if any(a.startswith(('bdist', 'build', 'install')) for a in sys.argv):
(pjoin('share', 'jupyter', 'kernels', KERNEL_NAME), glob(pjoin(dest, '*'))),
]
setuptools_args['zip_safe']=False
setuptools_args['eager_resources'] = ['yap_kernel']
setuptools_args['include_package_data']=True
extras_require = setuptools_args['extras_require'] = {
'test:python_version=="2.7"': ['mock'],
'test': ['nose_warnings_filters', 'nose-timer'],

View File

@ -1,3 +1,4 @@
"""An in-process kernel"""
# Copyright (c) IPython Development Team.

View File

@ -73,7 +73,6 @@ from IPython.utils.io import ask_yes_no
from IPython.utils.ipstruct import Struct
from IPython.paths import get_ipython_dir
from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
from IPython.utils.process import system, getoutput
from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
with_metaclass, iteritems)
from IPython.utils.strdispatch import StrDispatch
@ -93,7 +92,8 @@ bindvars = namedtuple('bindvars', 'list')
library = namedtuple('library', 'list')
v = namedtuple('_', 'slot')
load_files = namedtuple('load_files', 'file ofile args')
python_query = namedtuple('python_query', 'query_mgr string')
python_output = namedtuple('python_output', 'oldOut oldErryapi')
class YAPInteraction:
"""An enhanced, interactive shell for YAP."""
@ -114,9 +114,11 @@ class YAPInteraction:
# args.setYapPrologBootFile(os.path.join(yap_lib_path."startup.yss"))
self.yapeng = yap.YAPEngine(self.args)
self.q = None
self.yapeng.goal(use_module(library('yapi')))
self.shell = shell
self.run = False
self.yapeng.goal(use_module(library('python')))
self.yapeng.goal(use_module(library('yapi')))
self.yapeng.goal(python_output(OldOi ))
def eng(self):
return self.yapeng
@ -126,9 +128,41 @@ class YAPInteraction:
self.q.close()
self.q = None
def numbervars(self, l):
return self.yapeng.fun(bindvars(l))
def more(self):
if self.q.next():
if self.q.deterministic():
# done
self.q.close()
self.q = None
return True
self.q.close()
self.q = None
return False
def query_prolog(self, s):
if self.q:
return self.restart(s)
if not s:
return True
self.q = self.yapeng.qt(python_query(self,s))
# for eq in vs:
# if not isinstance(eq[0],str):
# print( "Error: Variable Name matches a Python Symbol")
# return False
return self.more()
def restart(self, s):
if s.startswith(';') or s.startswith('y'):
return self.more()
elif s.startswith('#'):
exec(s.lstrip('#'))
elif s.startswith('*'):
while self.more():
pass
print("No (more) answers")
self.q.close()
self.q = None
return False
def run_cell(self, s, store_history=True, silent=False,
@ -160,63 +194,48 @@ class YAPInteraction:
result : :class:`ExecutionResult`
"""
# construct a query from a one-line string
# q is opaque to Python
# vs is the list of variables
# you can print it out, the left-side is the variable name,
# the right side wraps a handle to a variable
# pdb.set_trace()
# #pdb.set_trace()
# atom match either symbols, or if no symbol exists, strings, In this case
# variable names should match strings
# ask = True
# launch the query
result = ExecutionResult()
result.execution_count = self.shell.execution_count
def error_before_exec(value):
result.error_before_exec = value
self.shell.last_execution_succeeded = False
if not s or s.isspace():
self.shell.last_execution_succeeded = True
return result
# inspect for ?? in the text
# print(st)
#
maxits = 2
if store_history:
result.execution_count = self.shell.execution_count
s = s.strip('\n\j\r\t ')
if not self.q or s:
(self.q,out) = self.top_level(s, out)
else:
out = q.next_answer()
if self.q:
st = s.strip('\n\j\r\t ')
if st and st == '*':
maxits = 1
elif st and st.isdigit():
maxits = int(st)*2
elif st and st != ';':
self.closeq()
if not self.q:
try:
if s:
self.q = self.yapeng.query(ya[q.__hash__])
self.vs = self.q.namedVarsVector()
else:
return
except SyntaxError:
return error_before_exec(sys.exc_info()[1])
cell = s # cell has to exist so it can be stored/logged
# Store raw and processed history
# if not silent:
# self.shell..logger.log(cell, s)
has_raised = False
try:
while (maxits != 0):
self.do_loop(maxits, gs)
except Exception:
result.error_in_exec = sys.exc_info()[1]
has_raised = True
self.closeq()
self.query_prolog(s)
self.shell.last_execution_succeeded = True
result.result = True
except Exception as e:
print(e)
self.shell.last_execution_succeeded = False
result.result = False
self.shell.last_execution_succeeded = not has_raised
result.result = self.shell.last_execution_succeeded
# Reset this so later displayed values do not modify the
# ExecutionResult
# self.displayhook.exec_result = None
# self.events.trigger('post_execute')
# if not silent:
# self.events.trigger('post_self.run_cell')
#self.events.trigger('post_execute')
#if not silent:
# self.events.trigger('post_run_cell')
if store_history:
# Write output to the database. Does nothing unless
# history output logging is enabled.
# self.history_manager.store_output(self.execution_count)
# Each cell is a *single* input, regardless of how many lines it has
self.shell.execution_count += 1
return result

View File

@ -12,6 +12,7 @@ from traitlets import Instance, Type, Any, List
from .comm import CommManager
from .kernelbase import Kernel as KernelBase
from .zmqshell import ZMQInteractiveShell
from .interactiveshell import YAPInteraction
class YAPKernel(KernelBase):
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',

View File

@ -1,63 +0,0 @@
# This is a CMake example for Python
INCLUDE(${SWIG_USE_FILE})
if (PYTHONLIBS_FOUND)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/CXX)
SET(CMAKE_SWIG_FLAGS "")
SET_SOURCE_FILES_PROPERTIES(../yap.i PROPERTIES CPLUSPLUS ON)
SET_SOURCE_FILES_PROPERTIES(../yap.i PROPERTIES SWIG_FLAGS "-includeall")
SET( CMAKE_SWIG_OUTDIR "${PROJECT_BINARY_DIR}/yap" )
SWIG_ADD_MODULE(py python ../yap.i )
SWIG_LINK_LIBRARIES (py Yap++ )
add_dependencies(py Yap++ )
configure_file ("setup.py.cmake"
"yap/setup.py" )
add_custom_target ( PyYAP ALL
COMMAND ${PYTHON_EXECUTABLE} setup.py install
WORKING_DIRECTORY "yap"
DEPENDS python Yap++)
if ( DOCUMENTATION AND DOXYGEN_FOUND )
set(CMAKE_SWIG_FLAGS -DDOXYGEN=${DOXYGEN_FOUND})
# Run doxygen to only generate the xml
add_custom_command ( OUTPUT ${CMAKE_BINARY_DIR}/doc/xml/ftdi_8c.xml
COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/doc
COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_BINARY_DIR}/Doxyfile.xml
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
DEPENDS ${c_headers};${c_sources};${cpp_sources};${cpp_headers}
)
# generate .i from doxygen .xml
add_custom_command ( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/ftdi1_doc.i
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/doxy2swig.py -n
${CMAKE_BINARY_DIR}/doc/xml/ftdi_8c.xml
${CMAKE_CURRENT_BINARY_DIR}/ftdi1_doc.i
DEPENDS ${CMAKE_BINARY_DIR}/doc/xml/ftdi_8c.xml
)
add_custom_target ( doc_i DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/ftdi1_doc.i )
add_dependencies( ${SWIG_MODULE_ftdi1_REAL_NAME} doc_i )
endif ()
# add_subdirectory ( examples )
else ()
message(STATUS "Not building python bindings")
endif(PYTHONLIBS_FOUND)

View File

@ -10,6 +10,7 @@
// Language independent exception handler
%include exception.i
%include stdint.i
%include std_string.i
%ignore *::operator[];
@ -18,7 +19,7 @@ class YAPEngine;
#define arity_t size_t
#define Term uintptr_t
%{

View File

@ -217,7 +217,7 @@ load_files(Files,Opts) :-
'$lf_option'(if, 5, true).
'$lf_option'(imports, 6, all).
'$lf_option'(qcompile, 7, Current) :-
'$nb_getval'('$qcompile', Current, Current = never).
nb:nb:'$nb_getval'('$qcompile', Current, Current = never).
'$lf_option'(silent, 8, _).
'$lf_option'(skip_unix_header, 9, true).
'$lf_option'(compilation_mode, 10, Flag) :-
@ -258,7 +258,7 @@ load_files(Files,Opts) :-
setarg( Id, TOpts, Val ).
'$load_files'(Files, Opts, Call) :-
( '$nb_getval'('$lf_status', OldTOpts, fail), nonvar(OldTOpts) ->
( nb:'$nb_getval'('$lf_status', OldTOpts, fail), nonvar(OldTOpts) ->
'$lf_opt'(autoload, OldTOpts, OldAutoload)
;
'$lf_option'(last_opt, LastOpt),
@ -652,7 +652,7 @@ db_files(Fs) :-
'$do_lf'(_ContextModule, Stream, _UserFile, _File, _TOpts) :-
stream_property(Stream, file_name(Y)),
'$nb_getval'('$loop_streams',Sts0, Sts0 = []),
nb:'$nb_getval'('$loop_streams',Sts0, Sts0 = []),
lists:member(Stream0, Sts0),
stream_property(Stream0, file_name(Y)),
!.
@ -661,12 +661,12 @@ db_files(Fs) :-
stream_property(OldStream, alias(loop_stream) ),
'$lf_opt'(encoding, TOpts, Encoding),
set_stream( Stream, [alias(loop_stream), encoding(Encoding)] ),
'$nb_getval'('$loop_streams',Sts0, Sts0=[]),
nb:'$nb_getval'('$loop_streams',Sts0, Sts0=[]),
nb_setval('$loop_streams',[Stream|Sts0]),
'$lf_opt'('$context_module', TOpts, ContextModule),
'$lf_opt'(reexport, TOpts, Reexport),
'$lf_opt'(qcompile, TOpts, QCompiling),
'$nb_getval'('$qcompile', ContextQCompiling, ContextQCompiling = never),
nb:'$nb_getval'('$qcompile', ContextQCompiling, ContextQCompiling = never),
nb_setval('$qcompile', QCompiling),
% format( 'I=~w~n', [Verbosity=UserFile] ),
% export to process
@ -747,13 +747,13 @@ db_files(Fs) :-
'$q_do_save_file'(_File, _, _TOpts ).
'$reset_if'(OldIfLevel) :-
'$nb_getval'('$if_level', OldIfLevel, fail), !,
nb:'$nb_getval'('$if_level', OldIfLevel, fail), !,
nb_setval('$if_level',0).
'$reset_if'(0) :-
nb_setval('$if_le1vel',0).
'$get_if'(Level0) :-
'$nb_getval'('$if_level', Level, fail), !,
nb:'$nb_getval'('$if_level', Level, fail), !,
Level0 = Level.
'$get_if'(0).
@ -797,7 +797,7 @@ nb_setval('$if_le1vel',0).
fail.
'$exec_initialization_goals' :-
'$current_module'(M),
'$nb_getval'('$lf_status', TOpts, fail),
nb:'$nb_getval'('$lf_status', TOpts, fail),
'$lf_opt'( initialization, TOpts, Ref),
nb:nb_queue_close(Ref, Answers, []),
lists:member(G, Answers),
@ -845,7 +845,7 @@ nb_setval('$if_le1vel',0).
'$lf_opt'(encoding, TOpts, Encoding),
set_stream(Stream, [encoding(Encoding),alias(loop_stream)] ),
'$loaded'(Y, X, Mod, _OldY, _L, include, _, Dir, []),
( '$nb_getval'('$included_file', OY, fail ) -> true ; OY = [] ),
( nb:'$nb_getval'('$included_file', OY, fail ) -> true ; OY = [] ),
nb_setval('$included_file', Y),
print_message(informational, loading(including, Y)),
'$loop'(Stream,Status),
@ -955,7 +955,7 @@ prolog_load_context(file, FileName) :-
FileName = user_input
).
prolog_load_context(module, X) :-
'$nb_getval'('$consulting_file', _, fail),
nb:'$nb_getval'('$consulting_file', _, fail),
'$current_module'(X).
prolog_load_context(source, F0) :-
( source_location(F0, _) /*,
@ -1471,20 +1471,20 @@ If an error occurs, the error is printed and processing proceeds as if
'$get_if'(Level0),
Level is Level0 + 1,
nb_setval('$if_level',Level),
( '$nb_getval'('$endif', OldEndif, fail) -> true ; OldEndif=top),
( '$nb_getval'('$if_skip_mode', Mode, fail) -> true ; Mode = run ),
( nb:'$nb_getval'('$endif', OldEndif, fail) -> true ; OldEndif=top),
( nb:'$nb_getval'('$if_skip_mode', Mode, fail) -> true ; Mode = run ),
nb_setval('$endif',elif(Level,OldEndif,Mode)),
fail.
% we are in skip mode, ignore....
'$if'(_Goal,_) :-
'$nb_getval'('$endif',elif(Level, OldEndif, skip), fail), !,
nb:'$nb_getval'('$endif',elif(Level, OldEndif, skip), fail), !,
nb_setval('$endif',endif(Level, OldEndif, skip)).
% we are in non skip mode, check....
'$if'(Goal,_) :-
('$if_call'(Goal)
->
% we will execute this branch, and later enter skip
'$nb_getval'('$endif', elif(Level,OldEndif,Mode), fail),
nb:'$nb_getval'('$endif', elif(Level,OldEndif,Mode), fail),
nb_setval('$endif',endif(Level,OldEndif,Mode))
;
@ -1530,7 +1530,7 @@ no test succeeds the else branch is processed.
% we can try the elif
'$elif'(Goal,_) :-
'$get_if'(Level),
'$nb_getval'('$endif',elif(Level,OldEndif,Mode),fail),
nb:'$nb_getval'('$endif',elif(Level,OldEndif,Mode),fail),
('$if_call'(Goal)
->
% we will not skip, and we will not run any more branches.
@ -1590,7 +1590,7 @@ End of conditional compilation.
set_prolog_flag(source, false).
'$fetch_comp_status'(assert_all) :-
'$nb_getval'('$assert_all',on, fail), !.
nb:'$nb_getval'('$assert_all',on, fail), !.
'$fetch_comp_status'(source) :-
current_prolog_flag(source, true), !.
'$fetch_comp_status'(compact).

View File

@ -24,6 +24,10 @@
:- use_system_module( '$_modules', ['$do_import'/3]).
:- multifile user:system_foreign/1.
/**
@defgroup LoadForeign Access to Foreign Language Programs